Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - Return a sorted copy of the index
To return a sorted copy of the index, use the index.sort_values() method in Pandas. This method creates a new sorted index without modifying the original.
Basic Syntax
index.sort_values(ascending=True, return_indexer=False)
Creating and Displaying Index
First, let's create a Pandas index with unsorted values ?
import pandas as pd
# Creating Pandas index
index = pd.Index([50, 10, 70, 95, 110, 90, 30])
# Display the original index
print("Original Pandas Index...")
print(index)
Original Pandas Index... Index([50, 10, 70, 95, 110, 90, 30], dtype='int64')
Sorting in Ascending Order
By default, sort_values() sorts in ascending order ?
import pandas as pd
index = pd.Index([50, 10, 70, 95, 110, 90, 30])
# Sort index values (ascending by default)
sorted_index = index.sort_values()
print("Sorted Index (Ascending)...")
print(sorted_index)
# Original index remains unchanged
print("\nOriginal Index unchanged...")
print(index)
Sorted Index (Ascending)... Index([10, 30, 50, 70, 90, 95, 110], dtype='int64') Original Index unchanged... Index([50, 10, 70, 95, 110, 90, 30], dtype='int64')
Sorting in Descending Order
Set ascending=False to sort in descending order ?
import pandas as pd
index = pd.Index([50, 10, 70, 95, 110, 90, 30])
# Sort index values in descending order
sorted_desc = index.sort_values(ascending=False)
print("Sorted Index (Descending)...")
print(sorted_desc)
Sorted Index (Descending)... Index([110, 95, 90, 70, 50, 30, 10], dtype='int64')
Working with String Index
The sort_values() method also works with string data ?
import pandas as pd
# Creating string index
str_index = pd.Index(['apple', 'zebra', 'banana', 'cherry'])
print("Original String Index...")
print(str_index)
# Sort string index
sorted_str = str_index.sort_values()
print("\nSorted String Index...")
print(sorted_str)
Original String Index... Index(['apple', 'zebra', 'banana', 'cherry'], dtype='object') Sorted String Index... Index(['apple', 'banana', 'cherry', 'zebra'], dtype='object')
Key Points
| Parameter | Default | Description |
|---|---|---|
ascending |
True |
Sort in ascending or descending order |
return_indexer |
False |
Return indexer that sorts the index |
Conclusion
Use sort_values() to create a sorted copy of a Pandas index. The method preserves the original index and supports both ascending and descending order sorting.
Advertisements
