0
0
Pandasdata~5 mins

sort_index() for index sorting in Pandas

Choose your learning style9 modes available
Introduction
We use sort_index() to arrange data in order based on the row or column labels. This helps us find and understand data more easily.
When you want to see your data rows sorted by their labels.
When your data columns have labels and you want to reorder them alphabetically or numerically.
When you combine data from different sources and want to organize the index neatly.
When you want to prepare data for reports that require sorted labels.
When you want to quickly check if your data index is in order.
Syntax
Pandas
DataFrame.sort_index(axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, ignore_index=False, key=None)
axis=0 sorts rows by index; axis=1 sorts columns by their labels.
inplace=True changes the original data; inplace=False returns a new sorted copy.
Examples
Sorts the rows of df by their index labels in ascending order.
Pandas
df.sort_index()
Sorts the columns of df by their labels in descending order.
Pandas
df.sort_index(axis=1, ascending=False)
Sorts rows by index and updates df directly without making a copy.
Pandas
df.sort_index(inplace=True)
Sample Program
This example creates a DataFrame with index labels 2, 0, 1. Using sort_index() arranges the rows in order 0, 1, 2.
Pandas
import pandas as pd

# Create a DataFrame with unordered index
 data = {'Name': ['Anna', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
 df = pd.DataFrame(data, index=[2, 0, 1])

# Sort the DataFrame by its index
sorted_df = df.sort_index()
print(sorted_df)
OutputSuccess
Important Notes
sort_index() does not change the data inside rows or columns, only their order based on labels.
If your index has multiple levels (MultiIndex), you can sort by specific levels using the 'level' parameter.
Summary
sort_index() helps organize data by sorting row or column labels.
You can sort rows (axis=0) or columns (axis=1).
Use inplace=True to change the original DataFrame directly.