Python/Pandas中的布尔列比较 [英] Boolean column comparison in Python / Pandas

查看:232
本文介绍了Python/Pandas中的布尔列比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Pandas中获取包含布尔值的2列,并创建第三列,即这些布尔值的OR.

I am trying to take 2 columns in Pandas that contain Boolean values and create a third column that is the OR of these Boolean values.

例如,我的数据框当前包含A和B,并且我想创建C.

For example, my dataframe currently contains A and B, and I want to create C.

A B C
True True True
False False False
True False True
False True True

我的代码:

df['C']=df['A'] or df['B']

我试图以几种方式更改语句的结构,但最终得到相同的错误消息:

I have tried to change the structure of the statement several ways but end up with the same error message:

ValueError:系列的真值不明确.使用a.empty,a.bool(),a.item(),a.any()或a.all().

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

推荐答案

使用您不能在这里使用or运算符,因为它变得比较模棱两可.

You can't use or operator here as it becomes ambiguous comparing arrays.

或使用按位|运算符进行数组比较:

or use the bitwise | operator for array comparisons:

In [445]:
df['C'] = df['A'] | df['B']
df

Out[445]:
       A      B      C
0   True   True   True
1  False  False  False
2   True  False   True
3  False   True   True

这篇关于Python/Pandas中的布尔列比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆