注意:我正在Python 2.7.11中使用一个相当老的Pandas 0.16.2
。
我添加两个Series
的简单概念模型是它将涉及索引匹配步骤,类似于pd.concat(..., axis=1)
中发生的步骤,即。排列Series
索引,然后添加值。
因此(我猜测模NaN
处理),我希望u+v
只有当concat([u, v], axis=1)
有效时才能正常工作。
在下面的示例中,我构建了两个Series
,其中包含' unalignable'索引。我的困惑是concat
确实引发了错误(如预期的那样),但添加没有 - 更令人困惑的是,添加的结果会带来所有重复的内容。
首先,我创建了几个具有相同索引(包含重复项)的系列:
import string, pandas as pd
# Create a series with an index that has duplicates
u = pd.Series(range(5), index=list(string.ascii_lowercase)[:5])
u = pd.concat([u, u])
# Create another, same index but values reversed
v = pd.Series(range(5)[::-1], index=list(string.ascii_lowercase)[:5])
v = pd.concat([v, v])
他们是:
In [2]: u
Out[2]:
a 0
b 1
c 2
d 3
e 4
a 0
b 1
c 2
d 3
e 4
dtype: int64
In [3]: v
Out[3]:
a 4
b 3
c 2
d 1
e 0
a 4
b 3
c 2
d 1
e 0
dtype: int64
由于指数相等,可以添加它们:
In [4]: u+v
Out[4]:
a 4
b 4
c 4
d 4
e 4
a 4
b 4
c 4
d 4
e 4
dtype: int64
如果我们对v
进行排序,那么它的索引会被重新排序,因为不再有明显的方法将v
与u
对齐,{{1}就不足为奇了引发错误:
concat
然而,添加仍然有效,但奇怪的是返回更长的系列:
In [5]: v.sort()
In [6]: v
Out[6]:
e 0
e 0
d 1
d 1
c 2
c 2
b 3
b 3
a 4
a 4
dtype: int64
In [7]: pd.concat([u, v], axis=1)
....
ValueError: cannot reindex from a duplicate axis
这里发生了什么?