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

## How to sort a pandas dataframe?

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`

## Examples

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.

### 1. Sort dataframe by a single column

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:

**Data Science Programs By Skill Level**

**Introductory** ⭐

- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science

**Intermediate ⭐⭐⭐**

- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization

**Advanced ⭐⭐⭐⭐⭐**

- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science

**🔎 Find Data Science Programs 👨💻 111,889 already enrolled**

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

```
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
```

### 2. Sort dataframe by multiple columns

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.

### 3. Sort dataframe by putting NaNs first

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
```

### 4. Sort dataframe by a different sorting algorithm

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.**

More on Pandas DataFrames –

- Pandas – Sort a DataFrame
- Change Order of Columns of a Pandas DataFrame
- Pandas DataFrame to a List in Python
- Pandas – Count of Unique Values in Each Column
- Pandas – Replace Values in a DataFrame
- Pandas – Filter DataFrame for multiple conditions
- Pandas – Random Sample of Rows
- Pandas – Random Sample of Columns
- Save Pandas DataFrame to a CSV file
- Pandas – Save DataFrame to an Excel file
- Create a Pandas DataFrame from Dictionary
- Convert Pandas DataFrame to a Dictionary
- Drop Duplicates from a Pandas DataFrame
- Concat DataFrames in Pandas
- Append Rows to a Pandas DataFrame
- Compare Two DataFrames for Equality in Pandas
- Get Column Names as List in Pandas DataFrame
- Select One or More Columns in Pandas
- Pandas – Rename Column Names
- Pandas – Drop one or more Columns from a Dataframe
- Pandas – Iterate over Rows of a Dataframe
- How to Reset Index of a Pandas DataFrame?
- Read CSV files using Pandas – With Examples
- Apply a Function to a Pandas DataFrame