我有一个具有以下格式的数据框:
price cost
id mean max min mean max min
0 1 1 1 1 2 3
1 2 2 2 1 2 3
2 3 3 3 1 2 3
我想将其更改为以下内容:
id mean max min type
0 1 1 1 price
1 2 2 2 price
2 3 3 3 price
0 1 1 1 cost
1 2 2 2 cost
2 3 3 3 cost
最佳答案
尝试使用 stack()
方法、drop()
方法、reset_index()
方法和 rename()
方法:
df=(df.stack(0)
.drop('id',1)
.reset_index()
.rename(columns={'level_0':'id','level_1':'type'}))
df
的输出:
id type max mean min
0 0 cost 2 1 1
1 0 price 1 1 3
2 1 cost 2 1 2
3 1 price 2 2 3
4 2 cost 2 1 3
5 2 price 3 3 3
关于python - Pandas 转换多索引头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67578933/