首页 > 解决方案 > 以特定顺序在 Pandas 中取消堆叠数据框

问题描述

我有一些给定的数据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

如何设置索引的“顺序”?

标签: pythonpython-3.xpandasreshape

解决方案


dV = dU.reorder_levels((1,0), axis = 1).sort_index(axis = 1) 

推荐阅读