【问题标题】:How do I change the index values of a Pandas Series如何更改熊猫系列的索引值
【发布时间】:2020-01-04 09:31:31
【问题描述】:

(对不起,如果这个问题很愚蠢或不清楚,我是编程新手)

我想知道如何将 Pandas 系列的索引值从它们默认的常规整数值更改为我拥有的列表中的值。 例如

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 列表中的日期成为我创建的系列中的索引x

【问题讨论】:

    标签: python pandas series


    【解决方案1】:

    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:

    1. 方法链

      x.some_method().set_axis(index_values).another_method()
      
    2. 错误检查

      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)
    

    【讨论】:

      【解决方案2】:

      您可以通过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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-19
        • 1970-01-01
        • 2015-02-15
        • 1970-01-01
        • 2022-11-08
        • 2016-02-06
        • 2020-05-24
        • 2020-09-17
        相关资源
        最近更新 更多