0
0
Pandasdata~5 mins

Sorting by index in Pandas

Choose your learning style9 modes available
Introduction
Sorting by index helps you organize your data based on row or column labels, making it easier to find and analyze information.
When you want to arrange data rows in alphabetical or numerical order based on their labels.
When you need to prepare data for comparison or merging by aligning indexes.
When you want to display data in a specific order for reports or presentations.
When you want to quickly find data by sorted index labels.
When cleaning data to ensure consistent order after filtering or modifications.
Syntax
Pandas
DataFrame.sort_index(axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')
axis=0 sorts rows by index, axis=1 sorts columns by index.
ascending=True sorts from smallest to largest index; False sorts in reverse.
Examples
Sorts the DataFrame rows by index in ascending order.
Pandas
df.sort_index()
Sorts the DataFrame columns by their index labels in ascending order.
Pandas
df.sort_index(axis=1)
Sorts the DataFrame rows by index in descending order.
Pandas
df.sort_index(ascending=False)
Sorts the DataFrame rows by index and updates the original DataFrame.
Pandas
df.sort_index(inplace=True)
Sample Program
This creates a DataFrame with unordered index labels 'c', 'a', 'b'. Then it sorts the rows by index in ascending order ('a', 'b', 'c') and prints the result.
Pandas
import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
index = ['c', 'a', 'b']
df = pd.DataFrame(data, index=index)

sorted_df = df.sort_index()
print(sorted_df)
OutputSuccess
Important Notes
Sorting by index does not change the data inside rows or columns, only their order.
Use inplace=True to modify the original DataFrame without creating a new one.
Sorting columns by index is useful when column labels are meaningful and need ordering.
Summary
Sorting by index arranges data rows or columns based on their labels.
Use axis=0 for rows and axis=1 for columns.
ascending controls the order direction, and inplace controls if the original data changes.