I have just noticed this:
df[df.condition1 & df.condition2]
df[(df.condition1) & (df.condition2)]
Why does the output of these two lines differ?
I cannot share the exact data but I am going to try to provide as much detail as I can:
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
Solution
Thanks to @jezrael and @ayhan, here is what happened, and let me use the example provided by @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
If we take a look at row 3:
col1 col2
3 False 1.0
and the way I wrote the condition:
df.col1 == False & df.col2.isnull() # is equivalent to False == False & False
Because the &
sign has higher priority than ==
, without brackets False == False & False
is equivalent of:
False == (False & False)
print(False == (False & False)) # prints True
With brackets:
print((False == False) & False) # prints False
I think it is a bit easier to illustrate this problem with numbers:
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
So lessons learned: always add brackets!