python - 在 Pandas 中交换/订购多索引列

标签 python pandas dataframe multi-index

根据多索引文档代码,我执行以下操作:

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo'],
          ['one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))

index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])

df2 = pd.DataFrame(np.random.randn(3, 6), index=['A', 'B', 'C'], columns=index)

这会产生一个如下所示的数据框:

first        bar                 baz                 foo
second       one       two       one       two       one       two
A      -0.398965 -1.103247 -0.530605  0.758178  1.462003  2.175783
B      -0.356856  0.839281  0.429112 -0.217230 -2.409163 -0.725177
C      -2.114794  2.035790  0.059812 -2.197898 -0.975623 -1.246470

我的问题是,在我的输出(到 HTML 表格)中,我想根据二级索引而不是一级索引进行分组。产生的东西看起来像:

second       one                           two
first        bar       baz       foo       bar       baz       foo
A      -0.398965 -0.530605  1.462003 -1.103247  0.758178  2.175783
B      -0.356856  0.429112 -2.409163  0.839281 -0.217230 -0.725177
C      -2.114794  0.059812 -0.975623  2.035790 -2.197898 -1.246470

是否有一种简单的方法来交换和重新分组我的列索引?

最佳答案

swaplevelsort_index

df2.swaplevel(0, 1, 1).sort_index(1)

enter image description here

关于python - 在 Pandas 中交换/订购多索引列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40411300/

相关文章:

Python 正则表达式匹配非 ascii 名称

python - 使用偏移索引获取 pandas 中数据帧中列的第一个值

python - 与 pandas 数据框中的日期绘制保持一致

apache-spark - 如何使用 Dataset API 使用序数(例如 SQL 的 'GROUP BY 1' 或 'ORDER BY 2' )?

Python属性错误: 'Series' object has no attribute 'isdigit'

python - 如何在 Python 中查找并替换每行特定字符后面的文本?

python - pandas 根据同一列的值设置列

python - 使用计数器对象计算文件中的单词数

Python 和 Pandas : how to elegantly filter many dataframes?

python - 如何获得整个数据框而不是列的平均值?