Python 如何在多索引数据帧中手动排序列?

Python 如何在多索引数据帧中手动排序列?,python,pandas,multi-index,Python,Pandas,Multi Index,我有一个多索引数据框,我不想按字母顺序(axis=1)排序列,而是按自定义顺序排序。 我使用unstack将df转换为多索引,并使用sort_索引进行排序: df = df.unstack().swaplevel(1,0, axis=1).sort_index(axis=1, level=0) 我希望我的度量列按我的意愿排序,而不是按字母表排序,例如:metric2、metric3、metric1在椅子索引和表格索引中(以及更多) 请不要介意空值,这只是一个例子。改编自熊猫 现在检查 df.

我有一个多索引数据框,我不想按字母顺序(axis=1)排序列,而是按自定义顺序排序。 我使用unstack将df转换为多索引,并使用sort_索引进行排序:

df = df.unstack().swaplevel(1,0, axis=1).sort_index(axis=1, level=0)

我希望我的度量列按我的意愿排序,而不是按字母表排序,例如:metric2、metric3、metric1在椅子索引和表格索引中(以及更多)

请不要介意空值,这只是一个例子。

改编自熊猫

现在检查

df.columns.tolist()
[('bar', 'one'),
 ('bar', 'two'),
 ('baz', 'one'),
 ('baz', 'two'),
 ('foo', 'one'),
 ('foo', 'two'),
 ('qux', 'one'),
 ('qux', 'two')]
根据您的喜好重新排列并使用
.loc

df.loc[:,[('bar', 'one'),
('baz', 'one'),
 ('bar', 'two'),
('foo', 'one'),
 ('foo', 'two'),
 ('qux', 'two'),
 ('baz', 'two'),
 ('qux', 'one')
] ]
first        bar       baz       bar       foo                 qux       baz  \
second       one       one       two       one       two       two       two   
A       0.033707 -0.999368  0.681401 -0.417583 -0.233212 -0.850698 -0.015942   
B       1.140347 -0.278175 -0.759089 -0.642824 -0.902858  0.377443 -0.848010   
C      -0.370039 -0.404409 -0.425074 -0.985019 -0.971178 -1.129125 -1.090386   

first        qux  
second       one  
A      -0.072706  
B       0.117839  
C       0.924350
这种方法应该给你最大程度的控制

根据您的数据帧调整此方法,如下所示:

df = df.unstack().swaplevel(1,0, axis=1).loc[:, [('chair', 'metric2'),
        ('chair', 'metric3'), ('chair', 'metric1'),('table', 'metric2'),
        ('table', 'metric3'), ('table', 'metric1')]]
df.loc[:,[('bar', 'one'),
('baz', 'one'),
 ('bar', 'two'),
('foo', 'one'),
 ('foo', 'two'),
 ('qux', 'two'),
 ('baz', 'two'),
 ('qux', 'one')
] ]
first        bar       baz       bar       foo                 qux       baz  \
second       one       one       two       one       two       two       two   
A       0.033707 -0.999368  0.681401 -0.417583 -0.233212 -0.850698 -0.015942   
B       1.140347 -0.278175 -0.759089 -0.642824 -0.902858  0.377443 -0.848010   
C      -0.370039 -0.404409 -0.425074 -0.985019 -0.971178 -1.129125 -1.090386   

first        qux  
second       one  
A      -0.072706  
B       0.117839  
C       0.924350
df = df.unstack().swaplevel(1,0, axis=1).loc[:, [('chair', 'metric2'),
        ('chair', 'metric3'), ('chair', 'metric1'),('table', 'metric2'),
        ('table', 'metric3'), ('table', 'metric1')]]