两个Series对象的布尔比较
我有两个数据序列,它们的格式是这样的:
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
我想用这两个序列进行比较,创建一个新的序列,结果是布尔值(真或假)。大概是这样的:
result = foo and bar
>>> print result
0 False
1 False
2 False
3 True
4 True
Name: result, dtype: bool
如果我直接用 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().
我看过那些函数,但似乎都不能满足我的需求。
我该如何对两个序列进行逐元素的布尔比较,从而得到一个新的序列呢?
1 个回答
22
你需要使用按位与运算符 &
。
result = foo & bar