比较不同顺序的pandas.Series是否相等
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
我使用的是pandas 0.12.0版本。
1 个回答
5
你可以通过以下方式解决这个问题:
In [5]: x == y.reindex(x.index)
Out[5]:
A True
B True
C True
dtype: bool
或者
In [6]: x.sort_index() == y.sort_index()
Out[6]:
A True
B True
C True
dtype: bool
这里解释了“为什么”:https://github.com/pydata/pandas/issues/1134#issuecomment-5347816
更新:有一个讨论这个问题的帖子(https://github.com/pydata/pandas/issues/1134),还有一个修复这个问题的请求(https://github.com/pydata/pandas/pull/6860)