在Pandas数据帧布尔索引中使用“反向布尔”的正确方法

时间:2015-11-04 01:50:52

标签: python pandas indexing boolean

我想使用布尔索引,检查我的数据框的行,其中特定列的具有NaN值。所以,我做了以下几点:

import pandas as pd
my_df.loc[pd.isnull(my_df['col_of_interest']) == False].head()

查看该数据框的摘要,仅包含非NaN的值(大多数值为NaN)。

它有效,但似乎不那么优雅。我想输入:

my_df.loc[!pd.isnull(my_df['col_of_interest'])].head()

但是,这会产生错误。我也花了很多时间在R,所以也许我很困惑。在Python中,我通常会在语法中加入“not”。例如,if x is not none:,但我不能在这里真正做到。有更优雅的方式吗?我不喜欢进行毫无意义的比较。

2 个答案:

答案 0 :(得分:14)

通常使用pandas(和numpy),我们使用按位NOT ~而不是!not(其行为不能被类型覆盖)。< / p>

虽然在这种情况下我们有notnull~可以在没有特殊对立方法的情况下派上用场。

>>> df = pd.DataFrame({"a": [1, 2, np.nan, 3]})
>>> df.a.isnull()
0    False
1    False
2     True
3    False
Name: a, dtype: bool
>>> ~df.a.isnull()
0     True
1     True
2    False
3     True
Name: a, dtype: bool
>>> df.a.notnull()
0     True
1     True
2    False
3     True
Name: a, dtype: bool

(为了完整性,我注意到-(一元否定运算符)也适用于布尔系列,但~是规范选择,-已经不推荐使用numpy布尔数组。)

答案 1 :(得分:5)

您应该使用pandas.isnull()来查找列中没有空值的行,而不是使用pandas.notnull()。示例 -

import pandas as pd
my_df.loc[pd.notnull(my_df['col_of_interest'])].head()

pandas.notnull()pandas.isnull()的布尔逆,如文档中所示 -

  

另见
  pandas.notnull
  pandas.isnull的布尔反转