Sorting by Single Column

We wish to sort the rows of a data frame by the values of one column.

Ascending

We wish to sort a data frame in increasing order of the values of one column.

In this example, we wish to sort a data frame df in ascending order of the values of a column col_1.

df.sort_values(by='col_1')

Here is how this works:

  • We apply the function sort_values() to the data frame df.
  • We pass to sort_values() the name of the column we want to sort by which here is col_1.
  • By default, sort_values() sorts in ascending order.

Descending

We wish to sort a data frame in descending order of the values of one column.

In this example, we wish to sort a data frame df in descending order of the values of a column col_1.

df = df.sort_values(by="col_1", ascending=False)

Here is how this works:

  • We apply the function sort_values() to the data frame df.
  • We pass to sort_values() the name of the column we want to sort by which here is col_1.
  • To sort in descending order of the values of the sorting column, we set ascending=False. The default, as we saw above, is to sort in ascending order; i.e.ascending=True.

Ignore Index

Upon sorting a data frame, the rows keep their original row index. In some situations, we want to reset the row index so the rows of the sorted data frame would have an ordered index starting at 0 with the first row and ending at n-1 for the last row (where n is the number of rows in the data frame).

In this example, we wish to sort a data frame df in ascending order of the values of a column col_1 and wish to have the row index of the resulting sorted data frame be ordered.

df = df.sort_values(by='col_1', ignore_index=True)

Here is how this works:

  • We use sort_values() as described above to sort the data frame df in ascending order of the values of the column col_1.
  • To get an ordered axis index, we set the ignore_index parameter to True. The default is ignore_index=False.
PYTHON
I/O