Sort_index Python

A guide to sort_index python explained with Examples in 2023

In this tutorial, we will learn about the sort_index python method. We will understand the sort_index python method with several examples, so let’s get started.

sort_index python

The sort_index method is available in the pandas library. The sort_index method is used to sort a DataFrame by its row or column index.

Syntax of sort_index in python

The sort_index method in Pandas follows the below pattern:

df.sort_index(axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, by=None)

Where:

axis:			The axis to sort the data. 0 for index (rows) and 1 for columns. The default value is 0.

level:                 Specifies on which level of a multi-level index to sort the data.

ascending: 		Specifies the sorting order. True for ascending order and False for descending order.The default value is True.

inplace: 		Specifies if the sorting should take place in place (modifying the original DataFrame), or if a new sorted DataFrame should be       returned. The default value is False.

kind: 			Specifies the algorithm used for sorting like 'quicksort', 'mergesort', 'heapsort'. The default value is 'quicksort'.

na_position:	        Specifies the position of Null/NA values in the sorted data.

sort_remaining:        Specifies whether the remaining non-index levels should be sorted.

by: 			Specifies the names of the columns to sort by when sorting on a DataFrame with multiple columns.

sort_index python example

Sort_index Python example

In this session, we will understand the use of the python_sort method with various examples.

Python sort_index in a specific order

Let’s take the below example to sort the df in ascending order.

import pandas as pd

# create a  DataFrame
df = pd.DataFrame({'col1': [3, 2, 1], 'col2': [6, 5, 4], 'col3': [9, 8, 7]})

print(df)

# sort the DataFrame by row index
df.sort_index(ascending=False, inplace=True)

print(df)

The above code creates a Pandas DataFrame df with three columns col1, col2, and col3, and then sorts the DataFrame based on the row index using the sort_index method.

Please note that the inplace parameter is set to True, so the sorting is done in place and the original DataFrame is modified.

Python sort_index by multiindex

A user can also use the sort_index method to sort a dataframe that has one or more levels of the MultiIndex.Let’s take the below example:

import pandas as pd

# Create a sample DataFrame with a MultiIndex
df = pd.DataFrame({'col1': [3, 2, 1, 4], 'col2': [6, 5, 4, 7], 'col3': [9, 8, 7, 10]},
                  index=pd.MultiIndex.from_tuples([('i', 1), ('k', 2), ('c', 3), ('a', 4)],
                                                  names=['index1', 'index2']))
print(df)

# Sort the DataFrame based on the first level of the MultiIndex (index1) in descending order
df_sorted = df.sort_index(level=0)

print(df_sorted)

A Pandas DataFrame df with a MultiIndex composed of two levels index1 and index2, and three columns col1, col2, and col3.

The sort_index method sorts the DataFrame based on the first level of the MultiIndex index1 in descending order.

Python sort_index in a custom order

We can also sort the defame based on the custom list index. Let’s take the below example.

import pandas as pd

# create a  DataFrame
df = pd.DataFrame({'col1': [3, 2, 1], 'col2': [6, 5, 4], 'col3': [9, 8, 7]},index=['0', '1', '2'])

print(df)

# Specify the order of the index labels
order = ['0','2','1']

# sort the DataFrame by row index
new_df = df.reindex(order)

print(new_df)

The above code creates a Pandas DataFrame df with three columns col1, col2, and col3, and an index of labels 0, 1, and 2.

Then, a list order is created that specifies the desired order of the index labels. The reindex method is used to sort the DataFrame based on the specified order of the index labels.

Conclusion

Overall, sort_index is a simple and powerful method in pandas that allows for easy sorting of DataFrame and Series index labels in either ascending or descending order.

Please do let me know if you are facing any issues while following along.

More to Explore

Python __init__ method

Python __all__ method

python __new__ method

python __call__ method

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top