Pandas: 两个布尔系列的和

12 投票
2 回答
22827 浏览
提问于 2025-04-18 17:10

在Python中:

In [1]: True+True
Out[1]: 2

在进行以下设置之后:

import pandas as pd
ser1 = pd.Series([True,True,False,False])
ser2 = pd.Series([True,False,True,False])

我想要的是计算ser1ser2的逐个元素相加,像Python示例那样把布尔值当作整数来加。

但是Pandas把这个加法当成了逐个元素的“或”运算符,所以给出了以下(不想要的)结果:

In [5]: ser1+ser2
*/lib/python2.7/site-packages/pandas/computation/expressions.py:184: UserWarning: evaluating in Python space because the '+' operator is not supported by numexpr for the bool dtype, use '|' instead
  unsupported[op_str]))
Out[5]: 
0     True
1     True
2     True
3    False
dtype: bool

我知道可以通过对任一系列使用astype(int)来得到我想要的结果:

In [6]: ser1.astype(int) + ser2
Out[6]: 
0    2
1    1
2    1
3    0
dtype: int64

有没有其他(更“Pandas风格”)的方法来得到[2,1,1,0]这个系列?为什么简单的Series相加在这里不奏效,有什么好的解释吗?

2 个回答

6

不要用 +,用 & 来代替。

import pandas as pd
ser1 = pd.Series([True,True,False,False])
ser2 = pd.Series([True,False,True,False]) 

print(ser1 & ser2) 

>> 0     True
>> 1    False
>> 2    False
>> 3    False
>> dtype: bool
5

如果我理解得没错,你想要的其实是使用numpy的布尔数组,而不是Python的布尔值:

>>> a = True
>>> a+a
2
>>> import numpy as np
>>> np.array([a])
array([ True], dtype=bool)
>>> np.array([a]) + np.array([a])
array([ True], dtype=bool)

这个事情可以有不同的处理方式,记得至少有一个pandas的开发者对这种行为感到惊讶,但这样做是符合Series有类型这个概念的。

撰写回答