【问题标题】:Pandas: Change index of series while chainingPandas:链接时更改系列索引
【发布时间】:2021-05-19 09:50:39
【问题描述】:

假设我有一个熊猫系列

>>> s = pd.Series([1,2,3])
0 | 1
1 | 2
2 | 3

我可以通过以下方式更改索引

>>> s.index = ['a', 'b', 'c']
a | 1
b | 2
c | 3

但是我如何在链接时做到这一点,比如

s.apply(some_fun).<reindex to letters>.combine(...).etc.

【问题讨论】:

    标签: pandas indexing series


    【解决方案1】:

    有一个rename

    new_idx = ['a','b','c']
    s.rename(dict(zip(s.index, new_idx)))
    

    输出:

    a    1
    b    2
    c    3
    dtype: int64
    

    【讨论】:

      【解决方案2】:

      使用Series.set_axis:

      s = pd.Series([1,2,3])
      s = s.set_axis(['a', 'b', 'c'])
      
      print (s)
      a    1
      b    2
      c    3
      dtype: int64
      

      【讨论】:

        猜你喜欢
        • 2021-06-09
        • 1970-01-01
        • 2021-09-18
        • 1970-01-01
        • 2021-07-20
        • 2022-01-10
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多