Find Rolling Mean – Python Pandas

PythonServer Side ProgrammingProgramming

To find rolling mean, we will use the apply() function in Pandas. At first, let us import the required library −

import pandas as pd

Create a DataFrame with 2 columns. One is an int column −

dataFrame = pd.DataFrame(
   {
      "Car": ['Tesla', 'Mercedes', 'Tesla', 'Mustang', 'Mercedes', 'Mustang'],
      "Reg_Price": [5000, 1500, 6500, 8000, 9000, 6000]

   }
)

Group using GroupBy and find the Rolling Mean using apply() −

dataFrame.groupby("Car")["Reg_Price"].apply(
lambda x: x.rolling(center=False, window=2).mean())

Example

Following is the code −

import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['Tesla', 'Mercedes', 'Tesla', 'Mustang', 'Mercedes', 'Mustang'],
      "Reg_Price": [5000, 1500, 6500, 8000, 9000, 6000]
   }
)

print"DataFrame ...\n",dataFrame

print"\nRolling Mean...\n",dataFrame.groupby("Car")["Reg_Price"].apply(
lambda x: x.rolling(center=False, window=2).mean())

Output

This will produce the following output −

DataFrame ...
        Car   Reg_Price
0     Tesla       5000
1  Mercedes       1500
2     Tesla       6500
3   Mustang       8000
4  Mercedes       9000
5   Mustang       6000

Rolling Mean...
0       NaN
1       NaN
2    5750.0
3       NaN
4    5250.0
5    7000.0
Name: Reg_Price, dtype: float64
raja
Published on 17-Sep-2021 06:54:27
Advertisements