How to sort by multiple columns?

QuestionsQuestions8 SkillsProPandas Sorting DataNov, 05 2025
0147

To sort a DataFrame by multiple columns in Python using pandas, you can use the sort_values() method and pass a list of column names to the by parameter. Here’s an example:

import pandas as pd

# Sample DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'David'],
    'Age': [24, 30, 24, 30],
    'Score': [85, 90, 85, 95]
}

df = pd.DataFrame(data)

# Sort by 'Age' and then by 'Score'
sorted_df = df.sort_values(by=['Age', 'Score'])

print(sorted_df)

In this example, the DataFrame is sorted first by the 'Age' column and then by the 'Score' column. You can also specify the sorting order (ascending or descending) for each column by using the ascending parameter:

sorted_df = df.sort_values(by=['Age', 'Score'], ascending=[True, False])

This will sort 'Age' in ascending order and 'Score' in descending order.

0 Comments

no data
Be the first to share your comment!