行中的熊猫层次结构索引

时间:2019-05-17 01:25:44

标签: python pandas pandas-groupby multi-index

我认为这应该是一个小问题,但是我却无法找到解决方法。

假设您有以下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


1 个答案:

答案 0 :(得分:3)

Tmelt

之后的IIUC
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