How can I check if a Pandas dataframe's index is sorted?

Given a pandas dataframe, we have to check if a Pandas dataframe's index is sorted. By Pranit Sharma Last updated : October 03, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Index in pandas is just the number of rows defined in a Series or DataFrame. The index always starts from 0 to n-1 where n is the number of rows. The index is used in indexing which is a method of traversing or selecting particular rows and columns or selecting all the rows and columns.

Checking if a Pandas dataframe's index is sorted

Here, we are first going to create a DataFrame with specific indices and then we will use the is_monotonic() method which will allow us to check if the indices are in ascending order or not.

Let us understand with the help of an example,

Python program to check if a Pandas dataframe's index is sorted

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d1 = {'One':[i for i in range(10,100,10)]}

# Creating DataFrame
df = pd.DataFrame(d1)

# Display the DataFrame
print("Original DataFrame:\n",df,"\n")

# Using cut method
df['bins'] = pd.cut(df['One'],5)

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: check if a Pandas dataframe's index is sorted

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.