Sort pandas MultiIndex

前端 未结 1 1211
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 19:50

I have created a Dataframe with a MultiIndex by using another Dataframe:

arrays = [df[\'bus_uid\'], df[\'bus_type\'], df[\'type\'],
          df[\'obj_uid\']         


        
相关标签:
1条回答
  • 2020-12-06 20:04

    The answer depends on the pandas version you are working with. With the latest pandas (>= 0.17.0), you can indeed use the level keyword to specify to sort which level of the multi-index:

    df = df.sort_index(level=0)
    

    But, if you have an older pandas (< 0.17.0), this level keyword is not yet available, but you can use the sortlevel method:

    df = df.sortlevel(level=0)
    

    But note that if you want to sort all levels, you don't need to specify the level keyword, and you can just do:

    df = df.sort_index()
    

    This will work for both the recent and older versions of pandas.


    For a summary of these changes in the sorting API, see http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-sorting-api

    0 讨论(0)
提交回复
热议问题