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/