Python 大熊猫及;运算符未返回正确的值
在守则中:Python 大熊猫及;运算符未返回正确的值,python,pandas,dataframe,truthy,Python,Pandas,Dataframe,Truthy,在守则中: df = pd.DataFrame([[False, 0], [False, 1], [False, 2], [False, 2], [False, 3], [False, 4], [False, 5]], columns=['cond1', 'cond2']) df['test'] = (~df['cond1']) & (df['cond2']) 我希望在test列中得到除第一行以外的所有行中的值True,因为除0之外的任何数字的真值都是True。但是,
df = pd.DataFrame([[False, 0], [False, 1], [False, 2], [False, 2], [False, 3], [False, 4], [False, 5]],
columns=['cond1', 'cond2'])
df['test'] = (~df['cond1']) & (df['cond2'])
我希望在test
列中得到除第一行以外的所有行中的值True
,因为除0之外的任何数字的真值都是True
。但是,我得到了False
,其中cond2
中的值是2或4。为什么?
上述代码的输出:
cond1 cond2 test
0 False 0 False
1 False 1 True
2 False 2 False
3 False 2 False
4 False 3 True
5 False 4 False
6 False 5 True
当您对pandas列执行“&”操作时,python无法解释其他数字。它在做集合运算而不是布尔运算。因此,您需要通过将第二列转换为bool来帮助它:
df = pd.DataFrame([[False, 0], [False, 1], [False, 2], [False, 2], [False, 3], [False, 4], [False, 5]],
columns=['cond1', 'cond2'])
df['test'] = (~df['cond1']) & ((df['cond2'].astype(bool)))
如果您将
&
视为按位运算符,而不是布尔运算符,那么我就有意义了。