【发布时间】:2016-01-27 17:10:55
【问题描述】:
在 pandas 中,我想创建一个计算列,它是对另外两列的布尔运算。
在 pandas 中,将两个数值列相加很容易。我想用逻辑运算符AND 做类似的事情。这是我的第一次尝试:
In [1]: d = pandas.DataFrame([{'foo':True, 'bar':True}, {'foo':True, 'bar':False}, {'foo':False, 'bar':False}])
In [2]: d
Out[2]:
bar foo
0 True True
1 False True
2 False False
In [3]: d.bar and d.foo ## can't
...
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
所以我猜逻辑运算符的工作方式与 pandas 中的数字运算符不太一样。我尝试按照错误消息的建议执行操作并使用bool():
In [258]: d.bar.bool() and d.foo.bool() ## spoiler: this doesn't work either
...
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我找到了一种方法,将布尔列转换为int,将它们加在一起并作为布尔值进行评估。
In [4]: (d.bar.apply(int) + d.foo.apply(int)) > 0 ## Logical OR
Out[4]:
0 True
1 True
2 False
dtype: bool
In [5]: (d.bar.apply(int) + d.foo.apply(int)) > 1 ## Logical AND
Out[5]:
0 True
1 False
2 False
dtype: bool
这很复杂。有没有更好的办法?
【问题讨论】: