How to check the data present in a Series object is monotonically increasing or not?

PandasServer Side ProgrammingProgramming

To check if the data in the series is monotonically increasing or not, we can use the is_monotonic attribute of the pandas Series constructor.

The monotonically increasing is nothing but continuously increasing data. And the attribute “is_monotonic” is used to verify that the data in a given series object is always increasing or not.

In the pandas series constructor, we have another monotonic attribute for checking data increment which is nothing but is_monotonic_increasing (alias for is_monotonic).

Example 1

# importing required packages
import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series(np.random.randint(10,100, 10))
print(series)

print("Is monotonic: ", series.is_monotonic)

Explanation

In the following example, we initialized a Series with some random integer values created by using the NumPy random module. Then we applied the is_monotonic property on the series data.

Output

0 73
1 10
2 32
3 88
4 54
5 46
6 56
7 99
8 90
9 10
dtype: int32

Is monotonic: False

The output of the initial series object, as well as the output of the is_monotonic attribute, can be seen in the above output block.

The output for the is_monotonic attribute is a boolean value, for our example it is False. which means the data in the given series is not increasing continuously.

Example 2

import pandas as pd

# create a series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])

print(s)

print("Is monotonic: ", s.is_monotonic)

Explanation

In this example, we have initialized a series object, a python list of 10 integer values. After that, we applied the is_monotonic property to check the data of the series object.

Output

0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
9 10
dtype: int64

Is monotonic: True

We got the boolean value “False” as a result of the following example. which means the values present in the given series object is continuously increasing.

raja
Updated on 09-Mar-2022 06:19:41

Advertisements