python - 以特定顺序在 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
如何设置索引的“顺序”?
解决方案
dV = dU.reorder_levels((1,0), axis = 1).sort_index(axis = 1)
推荐阅读
- c++ - 如何将 vtkImageData 转换为 cv::Mat?
- python - 从多个文件中删除停用词 (NLTK)
- css - AutoPrefixer 不适用于 CSS 网格
- javascript - 如果使用 javascript 的 HTML 文档中存在某段文本,您如何提醒用户?
- apache-spark - 在 Scala Spark 的 DataFrame 列中用新值替换指定值
- c++ - 如何为使用 CMAKE 的交叉编译配置设置特定的 CMAKE_C_OUTPUT_EXTENSION?
- python - 无法满足的错误 conda-installing MySQL-python
- java - 我怎样才能得到这个ID?
- python - 安装 lib 表时出错,在 windows 中找不到 hdf5
- text-editor - 括号扩展停止工作