在数据框的两列上进行逻辑运算
问题说明
在熊猫中,我想创建一个计算列,该列是对另外两个列的布尔运算.
In pandas, I'd like to create a computed column that's a boolean operation on two other columns.
在熊猫中,很容易将两个数字列加在一起.我想对逻辑运算符AND
做类似的事情.这是我的第一次尝试:
In pandas, it's easy to add together two numerical columns. I'd like to do something similar with logical operator AND
. Here's my first try:
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().
因此,我想逻辑运算符的工作方式与熊猫中的数字运算符不太一样.我尝试执行错误消息建议的操作并使用bool()
:
So I guess logical operators don't work quite the same way as numeric operators in pandas. I tried doing what the error message suggests and using 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
并将它们加在一起并作为布尔值求值的方法.
I found a way that works by casting the boolean columns to int
, adding them together and evaluating as a boolean.
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
这令人费解.有更好的方法吗?
This is convoluted. Is there a better way?
正确答案
是的,还有更好的方法!只需使用&
元素级逻辑和运算符即可:
Yes there is a better way! Just use the &
element-wise logical and operator:
d.bar & d.foo
0 True
1 False
2 False
dtype: bool
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfkeff
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20