Eug*_*old 29 python series pandas
如何将 Pandas Series 的索引值从默认的常规整数值更改为我拥有的列表中的值?例如
x = pd.Series([421, 122, 275, 847, 175])
index_values = ['2014-01-01', '2014-01-02', '2014-01-03', '2014-01-04',
               '2014-01-05'] 
如何将列表中的日期index_values作为我创建的系列中的索引?
tdy*_*tdy 40
set_axis要更改现有系列的索引,请使用set_axis:
x = x.set_axis(index_values)
# 2014-01-01    421
# 2014-01-02    122
# 2014-01-03    275
# 2014-01-04    847
# 2014-01-05    175
# dtype: int64
优点x.index = index_values:
方法链接
x.some_method().set_axis(index_values).another_method()
错误检查
x.set_axis(list('abcdefg')) # ValueError: Length mismatch (Series:5, Index:7)
x.index = list('abcdefg') # No error despite mismatch
index参数如果您要创建新系列,请index在创建时使用参数:
x = pd.Series([421, 122, 275, 847, 175], index=index_values)
jez*_*ael 11
您可以通过以下方式分配索引值list:
x.index = index_values
print(x)
2014-01-01    421
2014-01-02    122
2014-01-03    275
2014-01-04    847
2014-01-05    175
dtype: int64