布尔值沿着pandas

时间:2017-01-11 14:26:47

标签: 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

我理解普通布尔索引是如何工作的,例如,如果我想选择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: Unalignable boolean Series key provided

那我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

IIUC你想使用布尔掩码来掩盖列:

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

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

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

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

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