Python 重建索引生成 Nan

Python Reindex Producing Nan

这是我正在使用的代码:

import pandas as pd

test3 = pd.Series([1,2,3], index = ['a','b','c'])
test3 = test3.reindex(index = ['f','g','z'])

所以最初一切都很好,test3 的索引为 'a' 'b' 'c',值为 1,2,3。但是当我重新索引 test3 时,我发现我的值 1 2 3 丢失了。这是为什么?所需的输出将是:

f 1
g 2
z 3

docs 对此行为很清楚:

Conform Series to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index

如果您只想覆盖索引值,请执行以下操作:

In [32]:
test3.index  = ['f','g','z']

test3
Out[32]:
f    1
g    2
z    3
dtype: int64