我有一些给定的数据d
:
import pandas as pd
import numpy as np
from collections import OrderedDict
table = OrderedDict((
("Item", ['Item0', 'Item0', 'Item1', 'Item1']),
('CType',['Gold', 'Bronze', 'Gold', 'Bronze']),
('USD', [1, 2, 3, 4]),
('EU', [1.1, 2.2, 3.3, 4.4])
))
d = pd.DataFrame(table)
我想 reshape 它。不是这个:
dU = d.set_index(['Item','CType']).unstack(['CType'])
dU
USD EU
CType Bronze Gold Bronze Gold
Item
Item0 2 1 2.2 1.1
Item1 4 3 4.4 3.3
但是为了:
Bronze Gold
CType EU USD EU USD
Item
Item0 2.2 2 1.1 1
Item1 4.4 4 3.3 3
如何设置索引的“顺序”?
最佳答案
dV = dU.reorder_levels((1,0), axis = 1).sort_index(axis = 1)
关于python - 按特定顺序在 Pandas 中取消堆叠 Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61346568/