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

Python 在pandas中交换/排序多索引列,python,pandas,dataframe,multi-index,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

按照有关多索引的文档代码,我执行以下操作:

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
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
我的问题是,在我的输出(到HTML表)中,我希望根据第二级索引而不是第一级索引进行分组。产生类似于:

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
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)是关键。我试过用swaplevel,但它不完全符合我的要求。谢谢