How to use the Series.expanding() function in pandas
Overview
The Series.expanding() function in the pandas library in Python lets us perform an expanding windows calculation over data in the given series.
Syntax
Series.expanding(min_periods=1, center=None, axis=0)
Parameters:
-
min_periods: This represents the minimum number of observations needed to have a value in the window. The default value isNone. -
center: This sets the labels of the window. The default isFalse. The window labels are set to the right edge of the window index if thecentervalue isFalse. Otherwise, the window labels are set at the center of the window index. -
axis: This is anintorstring. The default value is0. If theaxisis set to0orindex, the operation is performed across the rows. If theaxisis set to1orcolumns, the operation is performed across the columns.
Code example
The following code demonstrates how to use the Series.expanding() function in pandas:
import pandas as pd# Create the seriesseries=pd.Series(range(1,27,3), index=[x for x in 'educative'])# Print the seriesprint(series)# Return the expanding transformation of the series# using Series.expanding()print("Result of Series.expanding()")print(series.expanding(2).sum())
Code explanation
In the code above:
-
Line 1: We import the
pandaslibrary. -
Line 5: We create a
seriesusing therange()function and set the index toeducative. -
Line 7: We display the
serieselements. -
Lines 10–11: We calculate the expanding sum of data in the series over two observations using the
expanding()function.
Note: Since there is no element preceding the first element in the
series, thesumoperation could not be performed on the first element. Hence,NaNis returned.