Series.rolling()function offers a rolling windows function over data in the given Series.
Series.rolling(window, min_periods=None, center=False, win_type=None, axis=0, closed=None)
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 is
center: It sets the labels of the window. The default is
False, 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 be
string. The default value is
index, the operation is performed across the rows. If
columns, the operation is performed across the columns.
closed: It is used to close the interval on the ‘right’, ‘left’, ‘both’ or ‘neither’ endpoints.
The following code will demonstrate how to use the
Series.rolling() function in pandas.
import pandas as pd # create Series my_series = pd.Series([17, 9, 28, 15, 23, 7, 14]) # using rolling() to compute sum() print(my_series.rolling(2).sum())
In the code above, we see the following:
Lines 1–2: We import the
Line 5: We create the series,
Line 9: We calculate the sum of data in the series over a window size of 2 using the
Note: A NaN was returned for the first element in the series since there is no element before it, making the
View all Courses