python - 按特定顺序在 Pandas 中取消堆叠 Dataframe

标签 python python-3.x pandas reshape

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

相关文章:

python - 在 Pandas 中生成给定范围内的随机日期

python - wmctrl Cannot open display when Python open subprocess 如何修复

python - 如何在事先不知道名称的情况下调用类的实例

python-3.x - 线程 + 递归(需要 1 个位置参数,但给出了 39 个)

python - Python 3.6.0 中类内的方法是非本地的

python - 从 Python/Pandas Dataframe 的列表列中的列表中删除空格或 NaN

python - 如何将非分组列保留在 Pandas 的 groupBy 中

python - begin_nested() 是否自动回滚/提交?

python - 如何在 Python 中遍历给定 AST 的所有节点?

python - 关闭 python tkinter 中的所有窗口