How to Sort a DataFrame in Pandas by Two or More Columns?

Spread the love

Problem –

You want to sort a pandas dataframe by multiple columns.

Solution –

To sort a dataframe in pandas we use the sort_values() method.

Let’s read a dataset to work with.

import pandas as pd

url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/clothing_store_sales.csv"
df = pd.read_csv(url)
df.head()

Let’s say you want to sort the dataframe by Age and Net Sales. To do that, you will pass the name of the columns in a list to the by parameter.

df.sort_values(by=['Age', 'Net Sales'])

And if you want to sort the dataframe by a column in ascending order and another column in descending order, you will write.

df.sort_values(by=['Age', 'Net Sales'], ascending=[True, False])

Here, we sorted the Age column in ascending order and the Net Sales in descending order.

Related Posts –

  1. Pandas – sort_values() – How to sort pandas dataframe?

Rating: 1 out of 5.

Leave a Reply