How to sort values using Pandas

1 min readPandasDataFrame
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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.

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.