python-行中的熊猫层次结构索引
作者:互联网
我认为这应该是一个小问题,但是我无法找到解决方案.
假设您有以下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
解决方法:
T融化后的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
标签:multi-index,pandas-groupby,pandas,python 来源: https://codeday.me/bug/20191108/2005337.html