Python的大熊猫重组数据帧
问题描述:
我有以下数据框:Python的大熊猫重组数据帧
Type Label_1 Label_2 Label_3
A 1 5 3
B 3 2 1
C 2 1 2
我想格式化它看起来像这样:
Type Label_type Value
A Label_1 1
A Label_2 5
A Label_3 3
B Label_1 2
B Label_2 1
我怎样才能做到这一点的最有效的方法是什么?我没有这样做......
答
我们可以使用pd.melt方法:
In [87]: pd.melt(df, 'Type')
Out[87]:
Type variable value
0 A Label_1 1
1 B Label_1 3
2 C Label_1 2
3 A Label_2 5
4 B Label_2 2
5 C Label_2 1
6 A Label_3 3
7 B Label_3 1
8 C Label_3 2
如果顺序很重要:
In [89]: pd.melt(df, 'Type').sort_values(['Type', 'variable'])
Out[89]:
Type variable value
0 A Label_1 1
3 A Label_2 5
6 A Label_3 3
1 B Label_1 3
4 B Label_2 2
7 B Label_3 1
2 C Label_1 2
5 C Label_2 1
8 C Label_3 2
答
使用stack
:
df=df.set_index('Type').stack().rename_axis(('Type','Label_type')).reset_index(name='Value')
print (df)
Type Label_type Value
0 A Label_1 1
1 A Label_2 5
2 A Label_3 3
3 B Label_1 3
4 B Label_2 2
5 B Label_3 1
6 C Label_1 2
7 C Label_2 1
8 C Label_3 2
然后排序有必要 – jezrael
@jezrael,谢谢! – MaxU
这是完美的,非常感谢!不知道这之前:) – Maple123