直接上代码
import pandas as pd
import numpy as np
#生成行列格式数据
df=pd.DataFrame(np.random.randn(20).reshape(4,5),index=[['a','b','c','d']],columns=[10,20,30,40,50])
print(df)
#观察初始结构
# 10 20 30 40 50
#a 0.135203 -0.508673 0.772628 -1.415804 0.973777
#b -0.293076 -0.254650 2.138923 0.688851 1.413482
#c 0.875853 2.062340 1.347623 1.260754 -1.478119
#d -0.810309 0.628191 1.262556 -0.291155 -0.932978
res = df.stack()
print(res)
#a 10 0.135203
# 20 -0.508673
# 30 0.772628
# 40 -1.415804
# 50 0.973777
#b 10 -0.293076
# 20 -0.254650
# 30 2.138923
# 40 0.688851
# 50 1.413482
#c 10 0.875853
# 20 2.062340
# 30 1.347623
# 40 1.260754
# 50 -1.478119
#d 10 -0.810309
# 20 0.628191
# 30 1.262556
# 40 -0.291155
# 50 -0.932978
res= res.unstack(0)
print(res)
# a b c d
#10 0.135203 -0.293076 0.875853 -0.810309
#20 -0.508673 -0.254650 2.062340 0.628191
#30 0.772628 2.138923 1.347623 1.262556
#40 -1.415804 0.688851 1.260754 -0.291155
#50 0.973777 1.413482 -1.478119 -0.932978