How does the series.cummax() method work in Pandas?

PandasServer Side ProgrammingProgramming

The pandas Series.cummax() method is used to find the cumulative maximum of the elements in a series object.

The length of the output series has the same length as the input series object. The output series is returned from the series.cummax() method which consists of a cumulative maximum whereas the first element remains the same.

This method takes three parameters namely “axis”, “skipna” and additional keywords. The “skipna” parameter excludes Nan/null values by default, if we set it to “False” then it includes Nan/null values.

Example 1

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

# create a pandas Series object
series = pd.Series([10,22,14,np.nan,41,12])
print(series)

print("Cumulative maximum: ",series.cummax())

Explanation

In this example, we created a pandas series using a python list. The list object contains a Null value and some integer values. Then we applied the cummax() method without changing any default parameter values.

Output

0 10.0
1 22.0
2 14.0
3  NaN
4 41.0
5 12.0
dtype: float64

Cumulative maximum:
0 10.0
1 22.0
2 22.0
3  NaN
4 41.0
5 41.0
dtype: float64

The first element of the cummax series always has the same element from the original series. By default the cummax() method skips the execution of Nan values, hence the Nan value at position 3 is ignored.

Example 2

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

# create a pandas Series object
series = pd.Series([6,23,78,np.nan,89,34])
print(series)

print("Cumulative maximum: ",series.cummax(skipna=False))

Explanation

Same as the previous example, here also we initialized a pandas series object. And applied the cummax() method with setting the skipna value from True to False. This means it won’t ignore the Null/Nan values while executing.

Output

0  6.0
1 23.0
2 78.0
3  NaN
4 89.0
5 34.0
dtype: float64
Cumulative maximum: 0 6.0
1 23.0
2 78.0
3  NaN
4  NaN
5  NaN
dtype: float64

Up to the Nan value, we got the cumulative maximum elements. After that we got Nan values only, this is due to NaN compared with anything that returns NaN only.

raja
Updated on 09-Mar-2022 07:55:07

Advertisements