数据框两列的逻辑运算
Logical operation on two columns of a dataframe
在 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
这很复杂。有没有更好的方法?
是的,有更好的方法!只需使用 &
element-wise 逻辑与运算符:
d.bar & d.foo
0 True
1 False
2 False
dtype: bool
此外,还有另一种方法,您可以将其乘以 AND 或加法以得到 OR。没有像您那样进行转换和额外比较。
AND运算:
d.foo * d.bar
或运算:
d.foo + d.bar
d[(d['bar']) & (d['foo'])]
在 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
这很复杂。有没有更好的方法?
是的,有更好的方法!只需使用 &
element-wise 逻辑与运算符:
d.bar & d.foo
0 True
1 False
2 False
dtype: bool
此外,还有另一种方法,您可以将其乘以 AND 或加法以得到 OR。没有像您那样进行转换和额外比较。
AND运算:
d.foo * d.bar
或运算:
d.foo + d.bar
d[(d['bar']) & (d['foo'])]