Pandas: how to sort dataframe by column AND by index

前端 未结 3 609
不思量自难忘°
不思量自难忘° 2021-01-05 17:54

Given the DataFrame:

import pandas as pd
df = pd.DataFrame([6, 4, 2, 4, 5], index=[2, 6, 3, 4, 5], columns=[\'A\'])

Results in:

<         


        
3条回答
  •  生来不讨喜
    2021-01-05 18:41

    The other answers are great. I'll throw in one other option, which is to provide a name for the index first using rename_axis and then reference it in sort_values. I have not tested the performance but expect the accepted answer to still be faster.

    df.rename_axis('idx').sort_values(by=['A', 'idx'])

         A
    idx   
    3    2
    4    4
    6    4
    5    5
    2    6
    

    You can clear the index name afterward if you want with df.index.name = None.

提交回复
热议问题