熊猫:两个布尔系列的总和

时间:2014-08-13 16:44:50

标签: python pandas

在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

是否还有另一种(更“笨拙”)的方式来获得[2,1,1,0]系列?有没有一个很好的解释为什么简单的系列添加在这里不起作用?

2 个答案:

答案 0 :(得分:3)

IIUC,你正在寻找的是操作约定是numpy bool数组,而不是Python bools:

>>> 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)

可能已经走了两条道路,如果内存服务至少有一只大熊猫开发者对这种行为感到惊讶,但这样做就符合系列输入的想法。

答案 1 :(得分:1)

而不是+使用&

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
相关问题