按特定顺序在 Pandas 中拆分 Dataframe
Unstack a Dataframe in Pandas with certain order
我有一些给定的数据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)
我想重塑。不是这个:
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
如何设置索引的"order"?
dV = dU.reorder_levels((1,0), axis = 1).sort_index(axis = 1)
我有一些给定的数据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)
我想重塑。不是这个:
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
如何设置索引的"order"?
dV = dU.reorder_levels((1,0), axis = 1).sort_index(axis = 1)