Pandas DataFrame sort_index() Method

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

1. Overview and Syntax

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.

Method Signature: DataFrame.sort_index(axis=0, ascending=True, inplace=False, ignore_index=False)
Parameters:
• 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.
Returns: A sorted DataFrame object.

2. Descending Sort & Column Sorting (`axis=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)

3. Multi-Index Sorting

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

4. Frequently Asked Questions (FAQs)

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.

5. Common Errors & Troubleshooting

UnsortedIndexError / PerformanceWarning
Cause: Indexing or slicing unsorted MultiIndex DataFrames.
Fix: Call df.sort_index() prior to MultiIndex slicing.
Interactive Companion Jupyter Notebook

Explore interactive code cells, dynamically generate classes, test type vs isinstance comparisons, and run self-validating assertions.

View on GitHub Open In Colab

6. Related Tutorials




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer