Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python

How to obtain the cumulative maximum over a DataFrame axis

Onyejiaku Theophilus Chidalu

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 as 0 or 'index') or the column (designated as 1 or columns) 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 library
import pandas as pd

# creating a dataframe
df = pd.DataFrame([[5,10,4,15,3],
                   [1,7,5,9,0.5],
                   [3,11,13,14,12]],
                   columns=list('ABCDE'))
# printing the dataframe
print(df)

# obtaining the cummulative maximum vertically across rows
print(df.cummax(axis="index"))

# obtaining the cummulative maximum horizontally over columns
print(df.cummax(axis="columns"))
Syntax for the cummax() function

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.

RELATED TAGS

pandas
python

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring