How to obtain the cumulative maximum over a DataFrame axis
Overview
We use the cummax() function of a DataFrame object to obtain the cumulative maximum over its axis.
Axis here represents the row and column of the DataFrame. The axis with a value of
'0'indicates the axes that run vertically downwards across a row, while a value of'1'shows the axes that run horizontally across a column.
Syntax
The cummax() function takes the syntax shown below:
DataFrame.cummax(axis=None, skipna=True, *args, **kwargs)
Syntax for the cummax() function in Pandas
Parameters
The cummax() function takes the following parameter values:
axis: This represents the name for the row (designated as0or'index') or the column (designated as1orcolumns) axis.skipna(optional): This takes a Boolean value indicating if NA or null values are to be excluded or not.args,**kwargs(optional): These are keywords that have no effect but may be accepted for compatibility with NumPy.
Return value
The cummax() function returns a Series or DataFrame object showing the cumulative maximum in the axis.
Example
# A code to illustrate the cummax() function in Pandas# importing the pandas libraryimport pandas as pd# creating a dataframedf = pd.DataFrame([[5,10,4,15,3],[1,7,5,9,0.5],[3,11,13,14,12]],columns=list('ABCDE'))# printing the dataframeprint(df)# obtaining the cummulative maximum vertically across rowsprint(df.cummax(axis="index"))# obtaining the cummulative maximum horizontally over columnsprint(df.cummax(axis="columns"))
Explanation
- Line 4 : We import the pandas library.
- Lines 7-10: We create a dataframe
df. - Line 12: We print the dataframe,
df. - Line 15: We obtain the cumulative maximum values running downwards across the rows (axis
0). We print the result to the console. - Line 18: We obtain the cumulative maximum values running horizontally across columns (axis
1). We print the result to the console.