0
0
Pandasdata~5 mins

Sorting by values in Pandas

Choose your learning style9 modes available
Introduction

Sorting by values helps you organize data so you can easily find the highest, lowest, or any order of values.

You want to see the top-selling products in a sales report.
You need to find the students with the highest grades.
You want to arrange dates from earliest to latest in a timeline.
You want to sort customer feedback scores from lowest to highest.
You want to prepare data for a report that requires ordered values.
Syntax
Pandas
DataFrame.sort_values(by, ascending=True, inplace=False)

by is the column name or list of columns to sort by.

ascending=True sorts from smallest to largest; use False for largest to smallest.

Examples
Sorts the DataFrame df by the column 'age' in ascending order.
Pandas
df.sort_values('age')
Sorts df by 'score' from highest to lowest.
Pandas
df.sort_values('score', ascending=False)
Sorts df first by 'city', then by 'age' within each city.
Pandas
df.sort_values(['city', 'age'])
Sample Program

This code creates a small table of people with their ages and scores. It first sorts the table by age from youngest to oldest, then sorts by score from highest to lowest.

Pandas
import pandas as pd

data = {'name': ['Anna', 'Bob', 'Cara', 'Dave'],
        'age': [28, 24, 35, 30],
        'score': [88, 92, 85, 90]}
df = pd.DataFrame(data)

# Sort by age ascending
sorted_by_age = df.sort_values('age')
print('Sorted by age:')
print(sorted_by_age)

# Sort by score descending
sorted_by_score = df.sort_values('score', ascending=False)
print('\nSorted by score (descending):')
print(sorted_by_score)
OutputSuccess
Important Notes

Sorting does not change the original DataFrame unless you use inplace=True.

You can sort by multiple columns by passing a list to by.

Summary

Use sort_values() to order data by one or more columns.

Set ascending=False to sort from largest to smallest.

Sorting helps you quickly find important or interesting data points.