Python Pandas - Return the integer indices that would sort the index

To return the integer indices that would sort the index, use the index.argsort() method in Pandas. This method returns an array of integers representing the positions that would sort the original index in ascending order.

Syntax

Index.argsort()

Basic Usage

Let's create a Pandas index and see how argsort() works ?

import pandas as pd

# Creating Pandas index
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')

# Display the original index
print("Original Index:")
print(index)

# Get the integer indices that would sort the index
sort_indices = index.argsort()
print("\nInteger indices for sorting:")
print(sort_indices)

# Apply the indices to see the sorted result
print("\nSorted index:")
print(index[sort_indices])
Original Index:
Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')

Integer indices for sorting:
[1 3 2 0 4]

Sorted index:
Index(['Accessories', 'Books', 'Decor', 'Electronics', 'Toys'], dtype='object', name='Products')

How It Works

The argsort() method analyzes the index values and returns the positions needed to achieve alphabetical order:

  • Position 1: 'Accessories' (comes first alphabetically)
  • Position 3: 'Books' (comes second)
  • Position 2: 'Decor' (comes third)
  • Position 0: 'Electronics' (comes fourth)
  • Position 4: 'Toys' (comes last)

Working with Numeric Index

The method also works with numeric indices ?

import pandas as pd

# Creating numeric index
numeric_index = pd.Index([45, 12, 78, 23, 5])

print("Original numeric index:")
print(numeric_index)

# Get sorting indices
sort_indices = numeric_index.argsort()
print("\nInteger indices for sorting:")
print(sort_indices)

# Apply sorting
print("\nSorted numeric index:")
print(numeric_index[sort_indices])
Original numeric index:
Index([45, 12, 78, 23, 5], dtype='int64')

Integer indices for sorting:
[4 1 3 0 2]

Sorted numeric index:
Index([5, 12, 23, 45, 78], dtype='int64')

Conclusion

The argsort() method returns integer indices that would sort the index, not the sorted index itself. Use these indices with bracket notation to get the actual sorted index. This is useful when you need to know the original positions of sorted elements.

Updated on: 2026-03-26T16:22:02+05:30

203 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements