python - pandas 中 DataFrame 沿行轴的 bool 索引

标签 python pandas

a = [ [1,2,3,4,5], [6,np.nan,8,np.nan,10]]
df = pd.DataFrame(a, columns=['a', 'b', 'c', 'd', 'e'], index=['foo', 'bar'])

In [5]: df
Out[5]: 
     a    b  c    d   e
foo  1  2.0  3  4.0   5
bar  6  NaN  8  NaN  10

我了解普通 bool 索引的工作原理,例如,如果我想选择具有 c > 3 的行,我会编写 df[df.c > 3] 。但是,如果我想沿着行轴执行此操作该怎么办?假设我只想要具有 'bar' == np.nan 的列。

由于 df['a']df.loc['bar'] 的相似之处,我认为以下应该可以做到这一点:

df.loc[df.loc['bar'].isnull()]

但事实并非如此,显然 results[results.loc['hl'].isnull()] 也没有给出相同的错误 *** pandas.core.indexing .IndexingError:提供了不可对齐的 bool 系列键

那么我该怎么做呢?

最佳答案

IIUC 您想要使用 bool 掩码来掩码列:

In [135]:
df[df.columns[df.loc['bar'].isnull()]]

Out[135]:
       b    d
foo  2.0  4.0
bar  NaN  NaN

或者您可以使用 ix 并将系列衰减为 np 数组:

In [138]:
df.ix[:,df.loc['bar'].isnull().values]

Out[138]:
       b    d
foo  2.0  4.0
bar  NaN  NaN

这里的问题是返回的 bool 系列是列上的掩码:

In [136]:
df.loc['bar'].isnull()

Out[136]:
a    False
b     True
c    False
d     True
e    False
Name: bar, dtype: bool

但是您的索引不包含这些列值作为标签,因此会出现错误,因此您需要对列使用掩码,或者您可以传递一个 np 数组来掩码 ix 中的列

关于python - pandas 中 DataFrame 沿行轴的 bool 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41593433/

相关文章:

python - 如何在执行某些操作时融化数据帧?

python - 如何在函数中将列表中的数字视为整数

python - 将空目录添加到 tarfile

python - Keras - 是否可以在 Tensorboard 中查看模型的权重和偏差

python - 计算 pandas 中的连续条件

python - 从 OLS 回归结果中获取偏斜和峰度

python - 使用 block 大小将 CSV 文件从 s3 加载到 Pandas

python - sqlalchemy 日期错误。参数 'arg' 预期为 STR 但得到 INT

python - 在 Salesforce 中使用默认值创建多个列

python - 无法在 Jupyter Notebook 中导入或安装 pandas-profiling