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 |
melted=df.melt('A')
meltedOut[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 |
reshaped=melted.pivot(index='A',columns='variable')
reshapedOut[32]:
value | ||
---|---|---|
variable | B | C |
A | ||
a | 1 | 2 |
b | 3 | 4 |
c | 5 | 6 |
reshaped.reset_index()Out[33]:
A | value | ||
---|---|---|---|
variable | B | C | |
0 | a | 1 | 2 |
1 | b | 3 | 4 |
2 | c | 5 | 6 |