比较pandas.Series在不同的顺序时是否相等

Dan*_*nov 6 python pandas

在应用二元运算符(如加法和减法)之前,Pandas会自动对齐Series对象的数据索引,但在检查相等性时不会这样做.为什么会这样,我该如何克服它?

请考虑以下示例:

In [15]: x = pd.Series(index=["A", "B", "C"], data=[1,2,3])

In [16]: y = pd.Series(index=["C", "B", "A"], data=[3,2,1])

In [17]: x
Out[17]:
A    1
B    2
C    3
dtype: int64

In [18]: y
Out[18]:
C    3
B    2
A    1
dtype: int64

In [19]: x==y
Out[19]:
A    False
B     True
C    False
dtype: bool

In [20]: x-y
Out[20]:
A    0
B    0
C    0
dtype: int64
Run Code Online (Sandbox Code Playgroud)

我正在使用熊猫0.12.0.

jor*_*ris 5

你可以用以下方法克服它:

In [5]: x == y.reindex(x.index)
Out[5]: 
A    True
B    True
C    True
dtype: bool
Run Code Online (Sandbox Code Playgroud)

要么

In [6]: x.sort_index() == y.sort_index()
Out[6]: 
A    True
B    True
C    True
dtype: bool
Run Code Online (Sandbox Code Playgroud)

这里解释'为什么':https://github.com/pydata/pandas/issues/1134#issuecomment-5347816

更新:有一个问题讨论这个(https://github.com/pydata/pandas/issues/1134)和一个公关来解决这个问题(https://github.com/pydata/pandas/pull/6860)