Python Pandas - Sort index values and also return the indices that would sort the index

PythonServer Side ProgrammingProgramming

To sort index values and also return the indices that would sort the index, use the index.sort_values(). The return_indexer parameter is set to be True.

At first, import the required libraries −

import pandas as pd

Creating Pandas index −

index = pd.Index([50, 10, 70, 95, 110, 90, 30])

Display the Pandas index −

print("Pandas Index...
",index)

Sort index values. By default, sorts in Ascending order. Return the indices to sort the index using the "return_indexer" parameter with value True −

print("
Sort and also return the indices that would sort the index...
",index.sort_values(return_indexer=True))

Example

Following is the code −

import pandas as pd

# Creating Pandas index
index = pd.Index([50, 10, 70, 95, 110, 90, 30])

# Display the Pandas index
print("Pandas Index...
",index) # Return the number of elements in the Index print("
Number of elements in the index...
",index.size) # Sort index values # By default, sorts in Ascending order # Return the indices to sort the index using the "return_indexer" parameter with value True print("
Sort and also return the indices that would sort the index...
",index.sort_values(return_indexer=True))

Output

This will produce the following output −

Pandas Index...
Int64Index([50, 10, 70, 95, 110, 90, 30], dtype='int64')

Number of elements in the index...
7

Sort and also return the indices that would sort the index...
(Int64Index([10, 30, 50, 70, 90, 95, 110], dtype='int64'), array([1, 6, 0, 2, 5, 3, 4], dtype=int64))
raja
Updated on 14-Oct-2021 06:45:16

Advertisements