Pandas Tutorial Pandas References

Pandas DataFrame - expanding() function



The Pandas DataFrame expanding() function provides expanding transformations.

Syntax

DataFrame.expanding(min_periods=1, center=None, 
                    axis=0, method='single')

Parameters

min_periods Optional. An int to specify minimum number of observations in window required to have a value (otherwise result is NA). Default is 1.
center Optional. If set to True, sets the labels at the center of the window. Default is False.
axis Optional. Specify the axis to use. For index, specify (0 or 'index') and for columns specify (1 or 'columns'). Default is 0.
method Optional. Execute the rolling operation per single column or row ('single') or over the entire object ('table'). Default is 'single'.

Return Value

Returns a Window sub-classed for the particular operation.

Example: expanding() example

In the example below, a DataFrame df is created. The expanding() function is used to create expanding transformations, which is further used to calculate rolling sum and rolling mean.

import pandas as pd
import numpy as np

#providing seed for reproducibility
#of the result
np.random.seed(10)

df = pd.DataFrame(np.random.randn(7, 3),
  index = pd.date_range('1/1/2018', periods=7),
  columns = ['col1', 'col2', 'col3']
)

#displaying the DataFrame
print(df)

#calculating the 4-day rolling sum
print("\ndf.expanding(4).sum() returns:")
print(df.expanding(4).sum())

#calculating the 4-day rolling mean
print("\ndf.expanding(4).mean() returns:")
print(df.expanding(4).mean())

The output of the above code will be:

                col1      col2      col3
2018-01-01  1.331587  0.715279 -1.545400
2018-01-02 -0.008384  0.621336 -0.720086
2018-01-03  0.265512  0.108549  0.004291
2018-01-04 -0.174600  0.433026  1.203037
2018-01-05 -0.965066  1.028274  0.228630
2018-01-06  0.445138 -1.136602  0.135137
2018-01-07  1.484537 -1.079805 -1.977728

df.expanding(4).sum() returns:
                col1      col2      col3
2018-01-01       NaN       NaN       NaN
2018-01-02       NaN       NaN       NaN
2018-01-03       NaN       NaN       NaN
2018-01-04  1.414114  1.878190 -1.058157
2018-01-05  0.449048  2.906464 -0.829527
2018-01-06  0.894186  1.769862 -0.694390
2018-01-07  2.378723  0.690057 -2.672118

df.expanding(4).mean() returns:
                col1      col2      col3
2018-01-01       NaN       NaN       NaN
2018-01-02       NaN       NaN       NaN
2018-01-03       NaN       NaN       NaN
2018-01-04  0.353529  0.469547 -0.264539
2018-01-05  0.089810  0.581293 -0.165905
2018-01-06  0.149031  0.294977 -0.115732
2018-01-07  0.339818  0.098580 -0.381731

❮ Pandas DataFrame - Functions