Python 与布尔运算不同的行为

Python 与布尔运算不同的行为,python,pandas,Python,Pandas,对于以下测试代码,有人能解释为什么第三行(索引2)的test1和test2的内容不同吗?我编写了一个latest1代码,在重新编写latest2来解决它之前,我浪费了几个小时试图找出代码不工作的原因。对于用于生成test1的一个线性程序,这是熊猫内部的操作顺序吗 import pandas as pd # test data dat1 = [1,1,2,1] dat2 = ['a','b','c','d'] # only for building a multi-column DF, not

对于以下测试代码,有人能解释为什么第三行(索引2)的
test1
test2
的内容不同吗?我编写了一个la
test1
代码,在重新编写la
test2
来解决它之前,我浪费了几个小时试图找出代码不工作的原因。对于用于生成
test1
的一个线性程序,这是熊猫内部的操作顺序吗

import pandas as pd

# test data
dat1 = [1,1,2,1]
dat2 = ['a','b','c','d'] # only for building a multi-column DF, not otherwise used
dat3 = [False,False,True,False]

# build a dataframe
df = pd.DataFrame( data={ "Data1":dat1, "Data2":dat2})

# first test
test1 = df['Data1']==1 | pd.Series(dat3)
print('==test 1==')
print(test1)

# second test
tmp1 = df['Data1']==1
tmp2 = pd.Series(dat3)
test2 = tmp1 | tmp2
print('==test 2==')
print(test2)
输出是

==test 1==
0     True
1     True
2    False
3     True
dtype: bool
==test 2==
0    True
1    True
2    True
3    True
dtype: bool

此差异是由运算符优先级引起的,请尝试:

test1 = (df['Data1']==1) | pd.Series(dat3) # Note the parenthesis (df['Data1']==1)
然后你会发现两者是相等的

# first test
test1 = (df['Data1']==1) | pd.Series(dat3)
print('==test 1==')
print(test1)

# second test
tmp1 = df['Data1']==1
tmp2 = pd.Series(dat3)
test2 = tmp1 | tmp2
print('==test 2==')
print(test2)

==test 1==
0    True
1    True
2    True
3    True
dtype: bool
==test 2==
0    True
1    True
2    True
3    True
dtype: bool

当您这样做时:

df['Data1']==1 | pd.Series(dat3)
评估如下:

df['Data1'] == (1 | pd.Series(dat3))
要避免这种情况,请对每个条件使用括号:

test1 = (df['Data1']==1) | pd.Series(dat3)

谢谢你对事物如何评估的澄清和解释,我想它一定很简单。