【问题标题】:Add a new index to a multi-indexed dataframe向多索引数据框添加新索引
【发布时间】:2018-08-24 13:23:36
【问题描述】:

我有一个 2 索引(日期、产品)数据框,如下所示:

[Date,Product]  price
D1 P1          1
   P2          4
D2 P1          2
   P2          2
D3 P1          2
   P2          3
...

如何从日期 D2 添加 P3 lvl,使其如下所示?

[Date,Product]  price
    D1 P1          1
       P2          4
    D2 P1          2
       P2          2
       P3          3
    D3 P1          2
       P2          3
       P3          1
    ...

【问题讨论】:

    标签: pandas dataframe indexing multi-index


    【解决方案1】:

    您可以使用pd.concat

    pd.concat([df,pd.DataFrame(data=[3,1],index=pd.MultiIndex.from_product([['D2','D3'],['P3']]),columns=['price'])]).sort_index()
    Out[68]: 
                  price
    Date Product       
    D1   P1           1
         P2           4
    D2   P1           2
         P2           2
         P3           3
    D3   P1           2
         P2           3
         P3           1
    

    【讨论】:

      猜你喜欢
      • 2018-10-17
      • 2017-06-10
      • 2013-12-03
      • 2020-04-16
      • 2017-04-30
      • 2020-03-12
      • 2018-12-06
      • 2013-04-11
      相关资源
      最近更新 更多