Pandas – Sort a DataFrame

In this tutorial, we’ll look at how to sort a pandas dataframe based on one or more column values with some examples.

You can use the pandas dataframe sort_values() function to sort a dataframe. It allows the flexibility to sort a dataframe by one or more columns, choose the sorting algorithm, how to treat NaNs during comparisons, using a custom key for sorting, etc. The following is the syntax:

df.sort_values(by, ascending=True, inplace=False)

Pass the column or list of columns to sort by to the by parameter. By default, it returns a sorted dataframe and does not alter the original dataframe. If you wish to modify the original dataframe in-place pass inplace=True

First, let’s create a dataframe that we’ll be using throughout this tutorial to sort.

import numpy as np
import pandas as pd

data = {
    'Name': ['Kobe Bryant', 'LeBron James', 'Michael Jordan', 'Larry Bird'],
    'Height': [198,206,198,206],
    'Championships': [5,4,6,3]
}

df = pd.DataFrame(data)
print(df)

Output:

              Name  Height  Championships
0     Kobe Bryant     198              5
1    LeBron James     206              4
2  Michael Jordan     198              6
3      Larry Bird     206              3

The dataframe df contains the height in cm and the number of championship victories of four of the most celebrated basketball players in the NBA.

Now, let’s look at some of the different use-cases of using the sort_values() function through some examples.

To sort a dataframe by a single column, pass the column name to the by parameter of the sort_values() function. For instance, to sort the above dataframe by Height:

df_sorted = df.sort_values(by='Height')
print(df_sorted)

Output:

             Name  Height  Championships
0     Kobe Bryant     198              5
2  Michael Jordan     198              6
1    LeBron James     206              4
3      Larry Bird     206              3

You can see that the returned dataframe is sorted on Height. Also notice that the returned dataframe retains the row indexes from the original dataframe. If you do not want to retain the indexes, pass ignore_index=True to the function or reset the index independently.

df_sorted = df.sort_values(by='Height', ignore_index=True)
print(df_sorted)

Output:

             Name  Height  Championships
0     Kobe Bryant     198              5
1  Michael Jordan     198              6
2    LeBron James     206              4
3      Larry Bird     206              3

You can also sort a pandas dataframe by multiple columns. For this, pass the columns by which you want to sort the dataframe as a list to the by parameter. Example, to sort the dataframe df by Height and Championships:

df_sorted = df.sort_values(by=['Height','Championships'])
print(df_sorted)

Output:

             Name  Height  Championships
0     Kobe Bryant     198              5
2  Michael Jordan     198              6
3      Larry Bird     206              3
1    LeBron James     206              4

In the above example, we sort the dataframe df by columns Height and Championships in the ascending order. That is, first by Height and then by Championships. You can see that Lebron James and Larry Bird have the same height but due to lesser number of championships Larry Bird is sorted above Lebron James.

If you want to sort a dataframe by a column which has one or more NaN values, you can decide to sort them first or last. This behavior is controlled by the parameter na_position which takes the values 'first' and 'last' and is 'last' by default. Here’s an example:

First, we create a copy of the original dataframe and set Michael Jordan’s height to NaN.

df_na = df.copy()
df_na.loc[2, 'Height'] = np.nan
print(df_na)

Output:

             Name  Height  Championships
0     Kobe Bryant   198.0              5
1    LeBron James   206.0              4
2  Michael Jordan     NaN              6
3      Larry Bird   206.0              3

Then, we sort the dataframe df_na by the column Height such that NaNs are put first on sorting.

df_na_sorted = df_na.sort_values(by='Height', na_position='first')
print(df_na_sorted)

Output:

             Name  Height  Championships
2  Michael Jordan     NaN              6
0     Kobe Bryant   198.0              5
1    LeBron James   206.0              4
3      Larry Bird   206.0              3

The sort_values() function also allows you to choose from three different sorting algorithms. The parameter kind controls this behavior. It takes 'quicksort', 'mergesort', and 'heapsort' as values and is 'quicksort' by default. For example, to sort a dataframe by a column using 'mergesort' as the sorting algorithm:

df_sorted = df.sort_values(by='Height', kind='mergesort')
print(df_sorted)

Output:

             Name  Height  Championships
0     Kobe Bryant     198              5
2  Michael Jordan     198              6
1    LeBron James     206              4
3      Larry Bird     206              3

The choice of the sorting algorithm does not change the result after sorting.

For more on the pandas sort_values() function, refer to its official documentation.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having numpy version 1.18.5 and pandas version 1.0.5


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.