我刚刚注意到这个:
为什么这两行代码的输出结果不同?
我不能分享具体的数据,但我会尽量提供尽可能多的细节:
如果我们看一下第三行:
而且我写条件的方式:
因为符号
带括号的:
我觉得用数字来说明这个问题会更容易一些:
df[df.condition1 & df.condition2]
df[(df.condition1) & (df.condition2)]
为什么这两行代码的输出结果不同?
我不能分享具体的数据,但我会尽量提供尽可能多的细节:
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
解决方案
感谢 @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
如果我们看一下第三行:
col1 col2
3 False 1.0
而且我写条件的方式:
df.col1 == False & df.col2.isnull() # is equivalent to False == False & False
因为符号
&
的优先级高于==
,所以没有括号的False == False & False
等同于:False == (False & False)
print(False == (False & False)) # prints True
带括号的:
print((False == False) & False) # prints False
我觉得用数字来说明这个问题会更容易一些:
print(5 == 5 & 1) # prints False, because 5 & 1 returns 1 and 5==1 returns False
print(5 == (5 & 1)) # prints False, same reason as above
print((5 == 5) & 1) # prints 1, because 5 == 5 returns True, and True & 1 returns 1
所以教训是:永远加上括号!
&
比==
具有更高的优先级。请参见更新的OP。 - Cheng