gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:36:51 24 4
gpt4 key购买 nike

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

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

我找到了一种通过将 bool 列转换为 int 的方法。 ,将它们加在一起并评估为 bool 值。
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

关于pandas - 对数据帧的两列进行逻辑运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35043739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com