w3resource

Pandas - Applying a custom Rolling average function

Pandas: Custom Function Exercise-18 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/pandas-apply-a-custom-rolling-average-function-to-dataframe-columns.php