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 in descending order
To return a sorted copy of the index in descending order, use the index.sort_values() method in Pandas. Set the ascending parameter to False to sort in descending order.
Syntax
Index.sort_values(ascending=True, return_indexer=False, key=None)
Parameters
The main parameters are:
- ascending: Boolean, default True. If False, sort in descending order
- return_indexer: Boolean, default False. If True, returns the indices that would sort the index
- key: Function, optional. Apply function before sorting
Example
Let's create a Pandas index and sort it in descending order:
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)
# Sort index values in descending order
sorted_index = index.sort_values(ascending=False)
print("\nSorted index (descending order):")
print(sorted_index)
Original Pandas Index: Index([50, 10, 70, 95, 110, 90, 30], dtype='int64') Sorted index (descending order): Index([110, 95, 90, 70, 50, 30, 10], dtype='int64')
Sorting String Index
The method also works with string indices:
import pandas as pd
# Creating string index
str_index = pd.Index(['zebra', 'apple', 'mango', 'banana'])
print("Original string index:")
print(str_index)
# Sort in descending order
sorted_str = str_index.sort_values(ascending=False)
print("\nSorted string index (descending):")
print(sorted_str)
Original string index: Index(['zebra', 'apple', 'mango', 'banana'], dtype='object') Sorted string index (descending): Index(['zebra', 'mango', 'banana', 'apple'], dtype='object')
Key Points
- The
sort_values()method returns a new sorted copy and doesn't modify the original index - Set
ascending=Falsefor descending order - Works with numeric, string, and datetime indices
- The original index remains unchanged
Conclusion
Use index.sort_values(ascending=False) to get a sorted copy of the index in descending order. This method preserves the original index while returning a new sorted version.
Advertisements
