27

Python Pandas provides two methods for sorting DataFrame :

What are differences between these two methods ?

nbro
  • 15,395
  • 32
  • 113
  • 196
working4coins
  • 1,997
  • 3
  • 22
  • 30

2 Answers2

22

As the question was updated to ask for the difference between sort_values (as sort is deprecated) and sort_index, the answer of @mathdan is no longer reflecting the current state with the latest pandas version (>= 0.17.0).

  • sort_values is meant to sort by the values of columns
  • sort_index is meant to sort by the index labels (or a specific level of the index, or the column labels when axis=1)

Previously, sort (deprecated starting from pandas 0.17.0) and sort_index where indeed almost identical (both methods could sort by both columns and index). But this confusing situation has been solved in 0.17.0.
For an overview of the changes in the sorting API, see http://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.17.0.html#changes-to-sorting-api

joris
  • 133,120
  • 36
  • 247
  • 202
  • It looks like the link that works now is: http://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.17.0.html#changes-to-sorting-api – Mike Mar 03 '19 at 01:06
6

The difference is entirely in the way it is called. The source code for sort is literally a one-line call to sort_index.

lindes
  • 9,854
  • 3
  • 33
  • 45
mathdan
  • 181
  • 1
  • 6