pandas 对数据帧的两列进行逻辑运算

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35043739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:41:58  来源:igfitidea点击:

Logical operation on two columns of a dataframe

pandasboolean-operations

提问by dinosaur

In pandas, I'd like to create a computed column that's a boolean operation on two other columns.

在 Pandas 中,我想创建一个计算列,它是对其他两列的布尔运算。

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:

在 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().

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():

所以我猜逻辑运算符的工作方式与熊猫中的数字运算符的工作方式不同。我尝试按照错误消息的建议进行操作并使用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().

I found a way that works by casting the boolean columns to int, adding them together and evaluating as a boolean.

我找到了一种方法,通过将布尔列转换为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

This is convoluted. Is there a better way?

这很复杂。有没有更好的办法?

回答by Kirell

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