两个Series对象的布尔比较

veo*_*eor 6 python pandas

我有两个系列,其格式与此相同:

0    False
1    False
2    False
3    True
4    True
Name: foo, dtype: bool

0    True
1    False
2    False
3    True
4    True
Name: bar, dtype: bool
Run Code Online (Sandbox Code Playgroud)

我想创建一个新系列,并从中得到布尔比较.像这样的东西:

result = foo and bar
>>> print result
0    False
1    False
2    False
3    True
4    True
Name: result, dtype: bool
Run Code Online (Sandbox Code Playgroud)

使用显而易见的result = foo and bar结果会导致以下错误:

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

我查看了这些功能,但似乎都没有按照我的意愿行事.

如何对系列进行元素到元素的布尔比较,从而产生新系列?

chr*_*isb 12

您需要使用按位和运算符&.

result = foo & bar
Run Code Online (Sandbox Code Playgroud)

  • 将数据框的列与某个值进行比较,然后执行布尔比较时,需要使用括号。例如,df ['column1']!='a'和df ['column2']!='b'将产生错误“无法将dtyped [object]数组与类型为[bool]的标量进行比较”。 。另一方面,`(df ['column1']!='a')&(df ['column2']!='b')`可以正常工作 (2认同)