Sorting data helps us see information clearly by putting it in order. We can arrange data from smallest to largest or largest to smallest.
0
0
Ascending and descending order in Pandas
Introduction
When you want to see the highest or lowest values in a list of numbers.
When you need to organize names or dates alphabetically or by time.
When preparing data for reports to show trends or rankings.
When cleaning data to find duplicates or errors by sorting.
When comparing different groups by sorting their values.
Syntax
Pandas
DataFrame.sort_values(by='column_name', ascending=True)
by is the column name you want to sort.
ascending=True sorts from smallest to largest; False sorts from largest to smallest.
Examples
Sorts the DataFrame by the 'Age' column from youngest to oldest.
Pandas
df.sort_values(by='Age', ascending=True)
Sorts the DataFrame by the 'Score' column from highest to lowest.
Pandas
df.sort_values(by='Score', ascending=False)
Sorts first by 'City' alphabetically, then by 'Age' descending within each city.
Pandas
df.sort_values(by=['City', 'Age'], ascending=[True, False])
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', 'Charlie', 'Diana'], 'Age': [28, 24, 35, 30], 'Score': [88, 92, 85, 90]} df = pd.DataFrame(data) # Sort by Age ascending sorted_by_age = df.sort_values(by='Age', ascending=True) print('Sorted by Age (ascending):') print(sorted_by_age) # Sort by Score descending sorted_by_score = df.sort_values(by='Score', ascending=False) print('\nSorted by Score (descending):') print(sorted_by_score)
OutputSuccess
Important Notes
If you want to sort the original DataFrame without creating a new one, use inplace=True.
You can sort by multiple columns by passing a list to by and a list of booleans to ascending.
Summary
Sorting helps organize data to understand it better.
Use ascending=True for smallest to largest, False for largest to smallest.
You can sort by one or more columns easily with pandas.