Skip to main content
 首页 » 编程设计

Python Pandas 重组数据框

2025年05月04日17powertoolsteam

我有以下数据框:

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