gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:15:01 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com