python运算符括号_python – pandas逻辑和带括号和不带括号的运算符会产生不同的结果...

参见英文答案 >

Logical operators for boolean indexing in Pandas                                    3个

我刚刚注意到了这一点:

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

如果我们看看第3行:

col1 col2

3 False 1.0

以及我写条件的方式:

df.col1 == False & df.col2.isnull() # is equivalent to False == False & False

因为& sign的优先级高于==,没有括号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

所以经验教训:总是添加括号!

我希望我能将答案分为@jezrael和@ayhan 🙁

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值