熊猫:两个布尔系列的和

exp*_*rer 5 python pandas

在Python中:

In [1]: True+True
Out[1]: 2
Run Code Online (Sandbox Code Playgroud)

因此,在进行以下设置之后:

import pandas as pd
ser1 = pd.Series([True,True,False,False])
ser2 = pd.Series([True,False,True,False])
Run Code Online (Sandbox Code Playgroud)

我想要的是找到ser1and 的元素明智的总和,ser2布尔值被视为整数,如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
Run Code Online (Sandbox Code Playgroud)

我知道我可以在任何一个系列上得到我想要的输出astype(int)

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

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

Cha*_*ton 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
Run Code Online (Sandbox Code Playgroud)


DSM*_*DSM 5

IIUC,您要寻找的是操作约定是 numpy bool 数组,而不是 Python bool:

>>> 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)
Run Code Online (Sandbox Code Playgroud)

两种方式都可以,如果没记错的话,至少有一个 pandas 开发人员对这种行为感到惊讶,但这样做符合系列输入的想法。

  • @exp1orer '+' 实际上是 '&','-' 是 '|' 对于这些布尔运算的元素聚合。由于“True”和“True”之和确实是未定义的。所以有人可能会说 python 实际上是在做一个非 pythonic 操作(它实际上是首先强制转换为 int )。但强制强制转换通常不会在 numpy/pandas 中完成。恕我直言,它不符合Python。 (2认同)