【问题标题】:Pandas Hierarchial index from row来自行的 Pandas 层次索引
【发布时间】:2019-10-04 07:32:45
【问题描述】:

我认为这应该是一个微不足道的问题,但是我不知何故无法找到解决方案。

假设你有以下 DF

pd.DataFrame({'Math_0':[1,2,6,'math'],'Math_1':[8,3,7,'math'],'science_0':[9,5,2,'science']},
             index=['Jeff','Bob','Cal','Category'])
df
>>>
        M0      M1      S1
Jeff    1       8       9
Bob     2       3       5
Cal     6       7       2
Subj    math    math    science

我想按索引行“Subj”分组以创建层次索引
反过来,生成的数据框看起来像

df
>>>
      Subj      question    score
Jeff  math      m0          1
                m1          8
      science   s0          9

Bob   math      m0          2
                m1          3
      science   s0          5

Cal   math      m0          6
                m1          7
      science   s0          2


【问题讨论】:

    标签: python pandas pandas-groupby multi-index


    【解决方案1】:

    T之后的IIUC做melt

    yourdf=df.T.reset_index().melt(['Subj','index']).set_index(['variable','Subj']).\
              rename(columns={'index':'question','value':'score'})
    
    yourdf
    Out[19]: 
                     question score
    variable Subj                  
    Jeff     math          M0     1
             math          M1     8
             science       S1     9
    Bob      math          M0     2
             math          M1     3
             science       S1     5
    Cal      math          M0     6
             math          M1     7
             science       S1     2
    

    【讨论】:

    • 哇,不错的答案 +1
    • 嗯,也许不像我最初想象的那么琐碎。这似乎是一个比我认为会在 pandas 中实现的更复杂的答案。还是谢谢你,我一回到我的电脑就会检查我的DF
    猜你喜欢
    • 2020-09-01
    • 2021-08-27
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    相关资源
    最近更新 更多