且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python Pandas按多索引和列排序

更新时间:2022-11-16 21:50:20

感觉可能有更好的方法,但这里有一种方法:

Feels like there could be a better way, but here's one approach:

In [163]: def sorter(sub_df):
     ...:     sub_df = sub_df.sort_values('C')
     ...:     sub_df.index = sub_df.index.droplevel(0)
     ...:     return sub_df

In [164]: df.groupby(level='A').apply(sorter)
Out[164]: 
                C   D
A   B                
bar two      dull   5
    three  glossy   8
    one     shiny  10
foo one      dull   3
    three    matt  12
    two     shiny   9