din*_*aur 22 boolean-operations pandas
在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().
Run Code Online (Sandbox Code Playgroud)
所以我猜逻辑运算符与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().
Run Code Online (Sandbox Code Playgroud)
我找到了一种方法,通过将布尔列转换为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
Run Code Online (Sandbox Code Playgroud)
这是令人费解的.有没有更好的办法?
Kik*_*ohs 38
是的,还有更好的方法!只需使用&元素逻辑和运算符:
d.bar & d.foo
0 True
1 False
2 False
dtype: bool
Run Code Online (Sandbox Code Playgroud)
小智 6
另外,还有另一种方法,您可以将“与”相乘或将“或”相加。没有像您所做的那样进行转换和额外比较。
与运算:
d.foo * d.bar
Run Code Online (Sandbox Code Playgroud)
或运算:
d.foo + d.bar
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23199 次 |
| 最近记录: |