在pandas中交换/排序多级索引列

14

按照多重索引的文档代码,我进行以下操作:

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

有没有一种简单的方法可以交换和重新分组我的列索引?

1个回答

24

1
.sort_index(1) 是关键。我尝试过 swaplevel,但它并没有完全做到我想要的。谢谢! - MarkD

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接