

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Rolling Mean – Python Pandas
<p>To find rolling mean, we will use the apply() function in Pandas. At first, let us import the required library −</p><pre class="just-code notranslate language-python" data-lang="python">import pandas as pd</pre><p>Create a DataFrame with 2 columns. One is an int column −</p><pre class="just-code notranslate language-python" data-lang="python" style="">dataFrame = pd.DataFrame( { "Car": ['Tesla', 'Mercedes', 'Tesla', 'Mustang', 'Mercedes', 'Mustang'], "Reg_Price": [5000, 1500, 6500, 8000, 9000, 6000] } )</pre><p>Group using GroupBy and find the Rolling Mean using apply() −</p><pre class="just-code notranslate language-python" data-lang="python" style="">dataFrame.groupby("Car")["Reg_Price"].apply( lambda x: x.rolling(center=False, window=2).mean()) </pre><h2>Example</h2><p>Following is the code −</p><pre class="demo-code notranslate language-python" data-lang="python" style="">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 ... ",dataFrame print" Rolling Mean... ",dataFrame.groupby("Car")["Reg_Price"].apply( lambda x: x.rolling(center=False, window=2).mean()) </pre><h2 style="">Output</h2><p>This will produce the following output −</p><pre class="result notranslate">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</pre>
- Related Questions & Answers
- Create a rolling mean column by displaying means to corresponding values in R data frame.
- Python - How to fill NAN values with mean in Pandas?
- What does series mean in pandas?
- Find Harmonic mean using Arithmetic mean and Geometric mean using C++.
- Python - Calculate the mean of column values of a Pandas DataFrame
- Print the mean of a Pandas series
- C++ Program to Implement Rolling Hash
- What does axes in the pandas series mean?
- What is the concept of Rolling Settlement?
- Find combined mean and variance of two series in Python
- Find Mean of a List of Numpy Array in Python
- Python – Get Matrix Mean
- Program to find mean of array after removing some elements in Python
- Implement mean shift algorithm in Python
- Python – Mean deviation of Elements
Advertisements