Python 按多索引数据帧在另一个数据帧上的显示顺序对多索引数据帧进行排序

Python 按多索引数据帧在另一个数据帧上的显示顺序对多索引数据帧进行排序,python,sorting,pandas,multi-index,Python,Sorting,Pandas,Multi Index,我有一个数据帧df如下: a b id no name T01 101 foo 1 $10 T32 102 bar 2 $30 T10 103 baz 4 $25 其中索引为id、no和name。我有另一个数据帧df2,它的索引顺序是我想要的 no 0 103 1 101 2 102 我需要的数据帧 a b id no name T10

我有一个数据帧
df
如下:

                 a   b
 id   no   name   
T01  101   foo   1  $10
T32  102   bar   2  $30
T10  103   baz   4  $25
其中索引为
id、no和name
。我有另一个数据帧
df2
,它的索引顺序是我想要的

    no
0  103
1  101
2  102
我需要的数据帧

                 a   b
 id   no   name  
T10  103   baz   4  $25 
T01  101   foo   1  $10
T32  102   bar   2  $30
我见过使用
df.loc[df2.no.values]
df.reindex(df2.no)
但由于我有多索引数据帧,它似乎不起作用


我应该使用什么来按照
df2
中的顺序对
df
键中的
no
进行排序?

一个可能的解决方案,最后一个:

如果级别顺序不重要:

print df1.reset_index(level=['id','name'])
         .reindex(df2.no)
         .set_index(['id','name'], append=True)

              a    b
no  id  name        
103 T10 baz   4  $25
101 T01 foo   1  $10
102 T32 bar   2  $30
计时

In [77]: %timeit df1.unstack([0, 2]).ix[df2.no].stack([1, 2]).swaplevel(0, 1)
10 loops, best of 3: 18.8 ms per loop

In [78]: %timeit df1.reset_index(level=['id','name']).reindex(df2.no).reset_index().set_index(['id','no','name'])
The slowest run took 4.41 times longer than the fastest. This could mean that an intermediate result is being cached 
100 loops, best of 3: 4.41 ms per loop
解决方案 解释
unstack([0,2])
将索引的第一级和第三级放入[-2,-1]级列中。这将隔离您关心的级别

ix[df2.no]
按您喜欢的顺序订购剩余级别

stack([1,2])
从列中获取级别并将它们放回索引中

swaplevel(0,1)
将索引级别恢复为原始顺序

In [77]: %timeit df1.unstack([0, 2]).ix[df2.no].stack([1, 2]).swaplevel(0, 1)
10 loops, best of 3: 18.8 ms per loop

In [78]: %timeit df1.reset_index(level=['id','name']).reindex(df2.no).reset_index().set_index(['id','no','name'])
The slowest run took 4.41 times longer than the fastest. This could mean that an intermediate result is being cached 
100 loops, best of 3: 4.41 ms per loop
df.unstack([0, 2]).ix[df2.no].stack([1, 2]).swaplevel(0, 1)