两列逻辑操作 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


这是令人困惑的。 有没有更好的办法?
已邀请:

龙天

赞同来自:

是的,有更好的方法! 只需使用基本逻辑运算符
&

和:


d.bar & d.foo

0 True
1 False
2 False
dtype: bool

要回复问题请先登录注册