Python - Rolling mean on pandas on a specific column

Learn, how can we find the rolling mean on pandas dataframe on a specific column with example? By Pranit Sharma Last updated : September 26, 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.

The average of a particular set of values is the called mean of that set. Mathematically, it can be represented as:

rolling mean formula

Find rolling mean on pandas on a specific column

Pandas allows us a direct method called mean() which calculates the average of the set passed into it. An average of the last n values in a data set, which is applied row-to-row, so that we can get a series of averages is called rolling average or rolling mean.

Pandas provides a feature called df['col'].rolling() which allows us to find the average of the last n rows. Here n is passed as a parameter.

Let us understand with the help of an example,

Python program to find rolling mean on pandas on a specific column

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'Year': [2017,2028,2029,2020,2021,2022], 
    'Month': ['January','Feburary','March','April','May','June'],

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame :\n",df,"\n")

# Adding a new column
df['new_col'] = df['Week'].rolling(3).mean()

# Display modified DataFrame
print("Modified DataFrame:\n",df)


The output of the above program is:

Example: Rolling mean on pandas on a specific column

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.