How to use the Series.rolling() function in Pandas
pandas Series.rolling() function
The pandas Series.rolling()function offers a rolling windows function over data in the given Series.
Syntax
Series.rolling(window, min_periods=None, center=False, win_type=None, axis=0, closed=None)
Parameters
-
window: It represents the size of the moving window. -
min_periods: It represents the minimum number of observations needed to have a value in the window. The default isNone. -
center: It sets the labels of the window. The default isFalse. IfFalse, the window labels are set at the right edge of the window index. Otherwise, the window labels are set at the center of the window index. -
win_type: It indicates the window type. -
axis: It can beintorstring. The default value is0. If0orindex, the operation is performed across the rows. If1orcolumns, the operation is performed across the columns. -
closed: It is used to close the interval on the ‘right’, ‘left’, ‘both’ or ‘neither’ endpoints.
Code example
The following code will demonstrate how to use the Series.rolling() function in pandas.
import pandas as pd# create Seriesmy_series = pd.Series([17, 9, 28, 15, 23, 7, 14])# using rolling() to compute sum()print(my_series.rolling(2).sum())
Code explanation
In the code above, we see the following:
-
Lines 1–2: We import the
pandaslibrary. -
Line 5: We create the series,
my_series. -
Line 9: We calculate the sum of data in the series over a window size of 2 using the
rolling()function.
Note: A NaN was returned for the first element in the series since there is no element before it, making the
sumoperation impossible.