w3resource

Pandas Series: cummax() function

Cumulative maximum over a Pandas DataFrame or Series axis

The cummax() function is used to get cumulative maximum over a DataFrame or Series axis.

Syntax:

Series.cummax(self, axis=None, skipna=True, *args, **kwargs)
Pandas Series cummax image

Parameters:

Name Description Type/Default Value Required / Optional
axis The index or the name of the axis. 0 is equivalent to None or ‘index’. {0 or ‘index’, 1 or ‘columns’}
Default Value: 0
Required
skipna Exclude NA/null values. If an entire row/column is NA, the result will be NA. boolean
Default Value: True
Required
*args, **kwargs Additional keywords have no effect but might be accepted for compatibility with NumPy. Required

Returns: scalar or Series

Example - Series:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([2, np.nan, 7, -3, 0])
s

Output:

0    2.0
1    NaN
2    7.0
3   -3.0
4    0.0
dtype: float64
Pandas Series cummax image

Example - By default, NA values are ignored:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([2, np.nan, 7, -3, 0])
s.cummax()

Output:

0    2.0
1    NaN
2    7.0
3    7.0
4    7.0
dtype: float64

Example - To include NA values in the operation, use skipna=False:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([2, np.nan, 7, -3, 0])
s.cummax(skipna=False)

Output:

0    2.0
1    NaN
2    NaN
3    NaN
4    NaN
dtype: float64

Example - DataFrame:

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame([[3.0, 2.0],
                   [5.0, np.nan],
                   [4.0, 0.0]],
                   columns=list('XY'))
df

Output:

  X	Y
0	3.0	2.0
1	5.0	NaN
2	4.0	0.0

Example - By default, iterates over rows and finds the maximum in each column. This is equivalent to axis=None or axis='index':

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame([[3.0, 2.0],
                   [5.0, np.nan],
                   [4.0, 0.0]],
                   columns=list('XY'))
df.cummax()

Output:

    X	Y
0	3.0	2.0
1	5.0	NaN
2	5.0	2.0

Example - To iterate over columns and find the maximum in each row, use axis=1:

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame([[3.0, 2.0],
                   [5.0, np.nan],
                   [4.0, 0.0]],
                   columns=list('XY'))
df.cummax(axis=1)

Output:

    X	Y
0	3.0	3.0
1	5.0	NaN
2	4.0	4.0

Previous: Compute covariance with Pandas Series
Next: Cumulative minimum over a Pandas DataFrame or Series axis



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/pandas/series/series-cummax.php