重新编制一个系列索引会在熊猫中返回NaN

时间:2018-06-13 13:42:10

标签: python-3.x pandas series multi-index reindex

以下代码返回一个包含NaNs的系列:

s = pd.Series([1, 2, 3, 4, 5, 6],
                 index=pd.MultiIndex.from_product([["A", "B"], ["c", "d", "e"]]))

s.reindex([('E', 'g'), ('E', 'h'), ('E', 'i'), ('F', 'g'), ('F', 'h'), ('F', 'i')])

s.reindex(pd.MultiIndex.from_product([['E', 'F'], ['g', 'h', 'i']]))

如何重新索引系列并保留原始值?

您的建议将不胜感激。

2 个答案:

答案 0 :(得分:3)

这不是reindex,即更改index

s.index=pd.MultiIndex.from_product([['E', 'F'], ['g', 'h', 'i']])
s
Out[362]: 
E  g    1
   h    2
   i    3
F  g    4
   h    5
   i    6
dtype: int64

答案 1 :(得分:1)

如果需要将新值设置为二级,请使用MultiIndex.set_levels

s.index = s.index.set_levels(['g', 'h', 'i'], level=1)
print (s)
A  g    1
   h    2
   i    3
B  g    4
   h    5
   i    6
dtype: int64