重新索引Series时,值将变为NaN

时间:2019-07-15 18:17:19

标签: python

import numpy as np
from pandas import DataFrame,Series
n = np.arange(0,5)
s = Series(n,index =['a','b','c','d','e'])
print(s)
s= s.reindex(['A','B','C','D','E'])
print(s)

输出:

a    0
b    1
c    2
d    3
e    4
dtype: int64
A   NaN
B   NaN
C   NaN
D   NaN
E   NaN
dtype: float64

1 个答案:

答案 0 :(得分:3)

使用以下脚本。它将把索引的值更改为您想要的值。重新索引不会更改值,但会更改记录的顺序,如果找不到该索引值,它将放入NaN。

OLD:

s= s.reindex(['A','B','C','D','E'])

新功能:

s.index=['A','B','C','D','E']

结果:

A    0
B    1
C    2
D    3
E    4
dtype: int64