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

Mik*_*son 7 python indexing boolean pandas

我想用一个布尔值索引,检查我的数据帧的行,其中特定的列并没有NaN值.所以,我做了以下事情:

import pandas as pd
my_df.loc[pd.isnull(my_df['col_of_interest']) == False].head()
Run Code Online (Sandbox Code Playgroud)

查看该数据框的片段,仅包括不是NaN(大多数值NaN)的值.

它起作用,但似乎不那么优雅.我想输入:

my_df.loc[!pd.isnull(my_df['col_of_interest'])].head()
Run Code Online (Sandbox Code Playgroud)

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

DSM*_*DSM 19

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

虽然在这种情况下,我们有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
Run Code Online (Sandbox Code Playgroud)

(为了完整性,我会注意到-,一元否定运算符,也将在布尔系列上工作,但是~是规范的选择,并且-已经为numpy布尔数组弃用了.)


Ana*_*mar 7

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

import pandas as pd
my_df.loc[pd.notnull(my_df['col_of_interest'])].head()
Run Code Online (Sandbox Code Playgroud)

pandas.notnull()pandas.isnull()文档中给出的布尔逆,

另请参见
pandas.notnull
pandas.isnull的boolean inverse