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 if the index is monotonic increasing (only equal or increasing) values
To check if a Pandas Index has monotonic increasing values (only equal or increasing), use the is_monotonic_increasing property. This property returns True if values never decrease, allowing for equal consecutive values.
Syntax
index.is_monotonic_increasing
Example with Monotonic Increasing Index
Let's create an index with monotonic increasing values ?
import pandas as pd
# Creating an index with monotonic increasing values
index = pd.Index([10, 20, 20, 30, 40])
# Display the index
print("Pandas Index...")
print(index)
# Check if the index is monotonic increasing
print("\nIs the Pandas index monotonic increasing?")
print(index.is_monotonic_increasing)
Pandas Index... Index([10, 20, 20, 30, 40], dtype='int64') Is the Pandas index monotonic increasing? True
Example with Non-Monotonic Index
Now let's test with an index that decreases ?
import pandas as pd
# Creating an index with decreasing values
index = pd.Index([40, 30, 20, 10])
# Display the index
print("Pandas Index...")
print(index)
# Check if the index is monotonic increasing
print("\nIs the Pandas index monotonic increasing?")
print(index.is_monotonic_increasing)
Pandas Index... Index([40, 30, 20, 10], dtype='int64') Is the Pandas index monotonic increasing? False
Comparison of Different Index Types
| Index Values | is_monotonic_increasing | Description |
|---|---|---|
| [10, 20, 30, 40] | True | Strictly increasing |
| [10, 20, 20, 30] | True | Equal values allowed |
| [40, 30, 20, 10] | False | Decreasing values |
| [10, 30, 20, 40] | False | Mixed order |
Practical Use Case
This property is useful for time series data validation ?
import pandas as pd
# Creating a DatetimeIndex
dates = pd.date_range('2024-01-01', periods=4, freq='D')
print("Date Index:")
print(dates)
print("\nIs monotonic increasing?")
print(dates.is_monotonic_increasing)
Date Index: DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04'], dtype='datetime64[ns]', freq='D') Is monotonic increasing? True
Conclusion
The is_monotonic_increasing property helps validate whether an index maintains non-decreasing order. This is particularly useful for time series data and sorted datasets where order matters.
Advertisements
