Pandas - Applying a custom Rolling average function
18. Rolling Window Calculation Using apply()
Write a Pandas program that applies apply() to perform a rolling window calculation.
This exercise shows how to use apply() to calculate a custom rolling window average over a DataFrame column.
Sample Solution :
Code :
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [5, 6, 7, 8, 9]
})
# Define a custom function to calculate the rolling average
def rolling_average(series, window):
return series.rolling(window=window).mean()
# Apply the function to column 'A' with a window of 2
df['A_rolling_avg'] = rolling_average(df['A'], window=2)
# Output the result
print(df)
Output:
A B A_rolling_avg 0 1 5 NaN 1 2 6 1.5 2 3 7 2.5 3 4 8 3.5 4 5 9 4.5
Explanation:
- Created a DataFrame with two columns 'A' and 'B'.
- Defined a custom function rolling_average() to compute the rolling average with a specified window size.
- Applied the rolling average function to column 'A' with a window size of 2.
- Added the rolling average as a new column 'A_rolling_avg' in the DataFrame.
For more Practice: Solve these Related Problems:
- Write a Pandas program to compute a rolling average on a time series column using apply() with a custom window function.
- Write a Pandas program to use apply() to perform a rolling window calculation and then compare the result with the built-in rolling().
- Write a Pandas program to create a custom function for a rolling sum and apply it via apply() to a DataFrame column.
- Write a Pandas program to calculate a rolling standard deviation on a DataFrame column using a custom function applied with apply().
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.