在 Python Pandas 中,布尔运算

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18952544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:10:53  来源:igfitidea点击:

In Python Pandas, boolean operation

pythonbooleanpandasseries

提问by python16

I am performing boolean operation on two Series. I was expecting the boolean operation to automatically do the operation corresponding to the same index. But instead it just does it by order. Is this the expected behavior or there is some different way of doing this? Thanks

我正在对两个系列执行布尔运算。我期待布尔操作自动执行与相同索引对应的操作。但它只是按顺序执行。这是预期的行为还是有一些不同的方式来做到这一点?谢谢

b
Out[47]: 
AEIS    False
AAPL     True
ACFN    False
Name: OldPosition, dtype: bool

a
Out[48]: 
AAPL     True
ACFN    False
AEIS     True
dtype: bool

a&b
Out[50]: 
AAPL    False
ACFN    False
AEIS    False
dtype: bool

回答by Andy Hayden

This seems like a bugto me:

这对我来说似乎是一个错误

In [1]: a = pd.Series([True, False, True], list('bca'))

In [2]: b = pd.Series([False, True, False], list('abc'))

In [3]: a & b
Out[3]:
b    False
c    False
a    False
dtype: bool

One way to workaround is to reindex using the same index:

一种解决方法是使用相同的索引重新索引:

In [4]: index = a.index | b.index

In [5]: a.reindex(index) & b.reindex(index)
Out[5]:
a    False
b     True
c    False
dtype: bool

回答by Cameron Stark

If you have the same length Series you should be able to use the index of one Series to order the other Series to line up to fit your needs.

如果您有相同长度的系列,您应该能够使用一个系列的索引来订购另一个系列以满​​足您的需求。

In [15]: a[b.index]
Out[15]:
a     True
b     True
c    False
dtype: bool

In [16]: b
Out[16]:
a    False
b     True
c    False
dtype: bool

In [17]: a[b.index] & b
Out[17]:
a    False
b     True
c    False
dtype: bool

I can confirm that as of pandas 0.17.1 the desired functionality is in place.

我可以确认,从 pandas 0.17.1 开始,所需的功能已经到位。

In [1]: import pandas as pd

In [2]: a = pd.Series([True, False, True], list('bca'))

In [3]: b = pd.Series([False, True, False], list('abc'))

In [4]: b & a
Out[4]:
a    False
b     True
c    False