【问题标题】:pandas multiindex columns rename熊猫多索引列重命名
【发布时间】:2022-11-21 19:24:09
【问题描述】:

您好我想重命名我的 df 的列。它有一个多索引列,我想更改它的第二级,即我有:

('GDP US Chained 2012 Dollars SAAR', 'GDP CHWG Index') ('GDP US Personal Consumption Chained 2012 Dollars SAAR', 'GDPCTOT Index') ('US Gross Private Domestic Investment Total Chained 2012 SAAR', 'GPDITOTC Index')
1969-12-31 00:00:00 4947.1 3052.12 593.659
1970-03-31 00:00:00 4939.76 3071.06 575.953
1970-06-30 00:00:00 4946.77 3084.97 577.205
1970-09-30 00:00:00 4992.36 3112.01 586.598
1970-12-31 00:00:00 4938.86 3103.57 555.454

我想更改第二行列并将“索引”替换为“”并删除“”。 我试过了 :

df.columns.get_level_values(1).str.lower().str.replace('index', '', regex=True).str.strip()

它有效,但我不能把它放在列名中

【问题讨论】:

    标签: python pandas rename multi-index


    【解决方案1】:
    df.columns = pd.MultiIndex.from_tuples([ (col0, col1.lower().replace('index', ''), *more_cols) for col0, col1, *more_cols in df.columns], names=df.columns.names)
    

    应该做

    【讨论】:

      【解决方案2】:

      rename 与 lambda 函数和参数 level=1 一起使用:

      L = [('GDP US Chained 2012 Dollars SAAR', 'GDP CHWG Index'),
          ('GDP US Personal Consumption Chained 2012 Dollars SAAR', 'GDPCTOT Index'),
          ('US Gross Private Domestic Investment Total Chained 2012 SAAR', 'GPDITOTC Index')]
      
      c = pd.MultiIndex.from_tuples(L)
      df = pd.DataFrame(columns=c, index=[0])
      
      df = df.rename(columns=lambda x: x.lower().replace('index','').strip(), level=1)
      print (df)
        GDP US Chained 2012 Dollars SAAR  
                                gdp chwg   
      0                              NaN   
      
        GDP US Personal Consumption Chained 2012 Dollars SAAR  
                                                      gdpctot   
      0                                                NaN      
      
        US Gross Private Domestic Investment Total Chained 2012 SAAR  
                                                            gpditotc  
      0                                                NaN            
      

      【讨论】:

        猜你喜欢
        • 2020-09-04
        • 2019-07-28
        • 1970-01-01
        • 2021-12-07
        • 2016-09-15
        • 2020-03-24
        • 2019-11-01
        • 2019-08-06
        • 1970-01-01
        相关资源
        最近更新 更多