相关疑难解决方法(0)

使用和不使用括号的pandas逻辑和运算符会产生不同的结果

我刚刚注意到了这一点:

df[df.condition1 & df.condition2]
df[(df.condition1) & (df.condition2)]
Run Code Online (Sandbox Code Playgroud)

为什么这两行的输出不同?


我无法分享确切的数据,但我会尝试尽可能多地提供详细信息:

df[df.col1 == False & df.col2.isnull()] # returns 33 rows and the rule `df.col2.isnull()` is not in effect
df[(df.col1 == False) & (df.col2.isnull())] # returns 29 rows and both conditions are applied correctly 
Run Code Online (Sandbox Code Playgroud)

感谢@jezrael和@ayhan,这里发生了什么,让我使用@jezael提供的示例:

df = pd.DataFrame({'col1':[True, False, False, False],
                   'col2':[4, np.nan, np.nan, 1]})

print (df)
    col1  col2
0   True   4.0
1  False   NaN
2  False   NaN
3  False   1.0
Run Code Online (Sandbox Code Playgroud)

如果我们看看第3行:

    col1  col2
3  False   1.0
Run Code Online (Sandbox Code Playgroud)

以及我写条件的方式:

df.col1 == False & df.col2.isnull() …
Run Code Online (Sandbox Code Playgroud)

python pandas

5
推荐指数
1
解决办法
1338
查看次数

标签 统计

pandas ×1

python ×1