import pandas as pd
df = pd.DataFrame({'VAL': [10, 20, 30]}, index=['b', 'c', 'a'])
print(df.sort_index())
Expected Output:
VAL
a 30
b 10
c 20
The DataFrame.sort_index() method sorts DataFrame objects by row index labels or column names. It is essential after operations like GroupBy, slicing, or appending that leave index labels unaligned or unsorted.
DataFrame.sort_index(axis=0, ascending=True, inplace=False, ignore_index=False)axis: 0 or 'index' (sort rows by index), 1 or 'columns' (sort columns alphabetically).ascending: Sort ascending (True) or descending (False).inplace: Modify DataFrame in-place (default False).ignore_index: Reset resulting index to 0, 1, ..., n-1.Sort row labels descending using ascending=False, or sort column names alphabetically across columns using axis=1.
import pandas as pd
df_data = pd.DataFrame({'Z_COL': [1, 2], 'A_COL': [3, 4]})
# Alphabetize column headers
df_sorted_cols = df_data.sort_index(axis=1)
print(df_sorted_cols)
In MultiIndex DataFrames, sort_index() sorts hierarchically across index levels.
import pandas as pd
tuples = [('b', 2), ('a', 2), ('a', 1)]
index = pd.MultiIndex.from_tuples(tuples, names=['LETTER', 'NUM'])
df_multi = pd.DataFrame({'SCORE': [10, 20, 30]}, index=index)
print(df_multi.sort_index())
Expected Output:
SCORE
LETTER NUM
a 1 30
2 20
b 2 10
Q: What is the difference between sort_values() and sort_index()?
sort_values() sorts DataFrames based on data values inside specified columns. sort_index() sorts based on row index labels or column headers.
Q: Does sort_index() alter the original DataFrame in-place?
No, by default it returns a sorted copy. Pass inplace=True to modify the original object directly.
df.sort_index() prior to MultiIndex slicing.
Explore interactive code cells, dynamically generate classes, test type vs isinstance comparisons, and run self-validating assertions.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.