Sort pandas dataframe both on values of a column and index?

后端 未结 8 1638
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 08:43

Is it feasible to sort pandas dataframe by values of a column, but also by index?

If you sort a pandas dataframe by values of a column, you can get the resultant dat

8条回答
  •  没有蜡笔的小新
    2020-12-13 09:11

    Pandas 0.23 finally gets you there :-D

    You can now pass index names (and not only column names) as parameters to sort_values. So, this one-liner works:

    df = df.sort_values(by = ['MyCol', 'MyIdx'], ascending = [False, True])
    

    And if your index is currently unnamed:

    df = df.rename_axis('MyIdx').sort_values(by = ['MyCol', 'MyIdx'], ascending = [False, True])
    

提交回复
热议问题