Pandas – sort_values() – How to sort pandas dataframe

Spread the love
sort dataframe in pandas

In this post, you will learn –

1 . How to sort a pandas dataframe by a column in ascending order.

2 . How to sort a pandas dataframe by a column in descending order.

3 . How to sort a pandas DataFrame by multiple columns.

1 . How to sort a pandas dataframe by a column in ascending order

Read the data to work with –

import pandas as pd

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

To sort a DataFrame by a column in ascending order, we use the DataFrame.sort_values() method. By Default df.sort_values() sort the data in ascending order.

Let’s say you want to sort the data by Age column. To do that you will write.

df.sort_values(by='Age')

2 . How to sort a pandas dataframe by a column in descending order

To sort a dataframe by a column in descending order, you need to set the ascending parameter to False.

Let’s sort the age column in descending order.

df.sort_values(by='Age', ascending=False)

3. How to sort a pandas DataFrame by multiple columns

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.

Rating: 1 out of 5.

Leave a Reply