【问题标题】:How can I get columns from Multi-Index?如何从多索引中获取列?
【发布时间】:2020-05-07 16:17:55
【问题描述】:

我有一个名为“keytable”的数据框,其中包含一个由“月”、“日”和“小时”组成的多索引。我想在创建 3 个具有“月”、“日”和“小时”值的新列时保留该多索引。我该怎么做? 这是数据框:

keytable.head()
Out[59]: 
                 pp    pres  rad    rh  ...   ws  WeekDay   Power_kW  Power_kW18
Month Day Hour                          ...                                     
1     3   0     0.0  1027.6  4.1  78.9  ...  0.0        3  77.303046  117.774419
          1     0.0  1027.0  3.3  79.7  ...  0.0        3  72.319602  110.710928
          2     0.0  1027.0  3.3  81.8  ...  0.0        3  71.831852  106.067667
          3     0.0  1027.0  1.9  86.6  ...  0.0        3  69.555751  106.325955
          4     0.0  1027.0  3.8  92.2  ...  0.0        3  69.525780  102.855393

[5 rows x 11 columns]

【问题讨论】:

  • 但它必须有非空值,所以它看起来像:(1,3,0), (1,3,1), (1,3,2), (1, 3,3), (1,3,4)....

标签: python pandas dataframe multi-index


【解决方案1】:

要创建名为“月”、“日”、“年”的新列,只需 new_table=key_table.reset_index() 会起作用。将索引复制为列是一种非常糟糕的做法,但如果你真的坚持,那么

newdf = new_table[['Year', 'Month', 'Year']].set_index(['Year', 'Month', 'Year']).
new_table.set_index(newdf.index, inplace=True) 

应该可以。

【讨论】:

    【解决方案2】:

    我最终做了一个 reset_index() 并取消删除了一个日期时间列,以便我可以重新索引它。

    keytable=keytable.reset_index()
    keytable['datetime'] = pd.to_datetime(keytable['datahora'].str.replace('/','-'), errors='coerce')
    keytable=keytable.set_index('datetime')
    

    【讨论】:

      猜你喜欢
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 2012-08-03
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多