How to sort values using Pandas

1 min

Pandas has a method called .sort_values() which gives the user an easy to sort any column in a Pandas DataFrame

We define a sample DataFrame

import pandas as pd

# We read a sample dataset from the web.
df = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
We read our sample dataset

You can download it here if the above script doesn't work for you and read it like so

import pandas as pd

# We read a sample dataset
df = pd.read_csv('./iris.csv')
We read our sample dataset

Sorting values

One column sorting

df.sort_values("sepal_length")
Sorting by one column, ascending way

It is by default in the ascending order, if you want the reverse you can use the ascending parameter.

df.sort_values("sepal_length", ascending=False)
Descending order

Two columns sorting

It is possible to sort by one or more columns.

Python will take the first column as primary filter then will use the second as secondary filter, etc...

In order to perform a two or more columns sorting, you will need to put the columns of interest within a list.

df.sort_values(["sepal_length", "sepal_width"])
Example of two columns sorting.

Here you are ! You now know how to sort values using Pandas.