如何更改Pandas Series的索引值?

28
我该如何将 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列表中的日期成为我创建的Series的索引?

2个回答

39

set_axis

使用set_axis来更改现有Series的索引:

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,具有以下优点:

  1. 方法链式化

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参数

    如果你正在创建一个新的Series,使用index参数来创建:

    x = pd.Series([421, 122, 275, 847, 175], index=index_values)
    

    set_axis()似乎不起作用。例如,尝试使用s=pd.Series(range(5))创建一个新系列,然后设置一个日期时间索引为pd.date_range('2020-01-01', periods=5, freq='1D')。然后检查s.index的值。使用set_axis()s.index是一个RangeIndex,但使用.index = ...,它是一个预期的DatetimeIndex - Jack M
    @JackM 在我的端上运行良好。这将按预期输出一个DatetimeIndex:s = pd.Series(range(5)); i = pd.date_range('2020-01-01', periods=5, freq='1D'); s = s.set_axis(i); print(s.index) - tdy
    1
    可能你只是执行了s.set_axis(i)而没有将s重新赋值为s = s.set_axis(i)。如果你不重新赋值,你需要使用s.set_axis(i, inplace=True),但请注意,inplace不被推荐使用并且最终会被弃用。详见此链接 - tdy
    1
    现在对.index的赋值操作会检查错误(或者至少检查长度不匹配的情况,例如:ValueError: Length mismatch: Expected axis has 5 elements, new values have 7 elements)。我不确定这个功能是从什么时候开始添加的,但我使用的是 Pandas 1.4.3 版本。 - wjandrea

    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
    

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接