python - Pandas :两个 bool 系列的总和

标签 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 的按元素求和, bool 值被视为用于加法的整数,如 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

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

最佳答案

代替 + 使用 &

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

关于python - Pandas :两个 bool 系列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25291753/

相关文章:

python - 检查路径在 Python 中是否有效

Python MySQLdb 模块 : can you insert or update without calling string format?

python - 如何提取特定字符之间的单词

Python-Pandas-Dataframe-datetime 转换排除空值单元格

python - 在 Pandas 中为层次索引的内部维度选择不同的值

python - 将代码写入文件,然后执行

python - "Internal Server Error"与 Hello World Python 应用程序

python - 在列表和元组列表之间查找公共(public) id

Python数据帧: fill text in certain rows if other columns satisfied

python - 有没有办法匹配两个数据帧中的序列号,并将 df2 中的系列列表(来自行)添加到 df1 中的新列中(Python,pandas)