How do pandas Rolling objects work?

Learn, how does pandas Rolling objects work in Python? By Pranit Sharma Last updated : October 05, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Working of rolling objects

The rolling function in pandas operates on pandas data frame columns independently. It is more than a python iterator and the most important point is that it computes nothing until you apply an aggregation function to it. When an aggregation is done, then a function that applies the rolling window of data is not used.

There may be confusion to the users that the rolling object acts as a dataframe but it actually does not act as a DataFrame. It is an object which can produce dataframes by applying aggregations over the window logic it houses.

We usually apply lambda for each cell of the new dataframe. It takes a window backward (along each column) from the old dataframe, and it aggregates it to one single cell in the new dataframe.

The aggregation can be of any type like sum, mean, user-defined, etc., over some window size (let us say 3.)

Let us understand with the help of an example,

Python program to demonstrate how does pandas Rolling objects work

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating DataFrame
df = pd.DataFrame(np.arange(5), columns=['a'])

# Display dataframe
print('Original DataFrame:\n',df,'\n')

# Applying rolling
res = df.rolling(3).mean().dropna()

# Display results
print("Results:\n",res,"\n")

Output

The output of the above program is:

Example: How do pandas Rolling objects work?

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.