df.melt(),df.pivot() 互为逆转函数
In [23]:
df=pd.DataFrame({'A':['a','b','c'],
'B':[1,3,5],
'C':[2,4,6]})
In [24]:
df
Out[24]:
| A | B | C |
0 |
a |
1 |
2 |
1 |
b |
3 |
4 |
2 |
c |
5 |
6 |
In [29]:
melted=df.melt('A')
melted
Out[29]:
| A | variable | value |
0 |
a |
B |
1 |
1 |
b |
B |
3 |
2 |
c |
B |
5 |
3 |
a |
C |
2 |
4 |
b |
C |
4 |
5 |
c |
C |
6 |
In [32]:
reshaped=melted.pivot(index='A',columns='variable')
reshaped
Out[32]:
| value |
variable | B | C |
A | | |
a |
1 |
2 |
b |
3 |
4 |
c |
5 |
6 |
In [33]:
reshaped.reset_index()
Out[33]:
| A | value |
variable | | B | C |
0 |
a |
1 |
2 |
1 |
b |
3 |
4 |
2 |
c |
5 |
6 |
标签:reshaped,df,melt,melted,pivot,Out
来源: https://www.cnblogs.com/liyun1/p/11273926.html