Computing a weighted rolling average #6761
-
I am trying to compute a weighted rolling average where each data point has a different weight. (My example is that I have monthly data, and I want each rolling window average to use the number of days in each month as a weight). The following code works, but I wanted to check if there is a better way to do it that doesn't rely on manual iteration of the DataArrayRolling objects. import xarray as xr
import numpy as np
window_size = 3
# Create one year of monthly data (twelve data points)
da = xr.DataArray(np.arange(0.,12.), coords={"time":np.arange("2022-01", "2023-01", dtype='datetime64[M]')})
month_weights = da.time.dt.daysinmonth # The numbers of days in each month are the desired weights
# Compute a weighted rolling average with manual iteration
da_rolling = da.rolling(time=window_size)
month_weights_rolling = month_weights.rolling(time=window_size)
result = da.copy()
for (da_label, da_window), (_, weights_window), in zip(da_rolling, month_weights_rolling):
result.loc[{"time" : da_label}] = da_window.weighted(weights_window.fillna(0)).mean("time") This is the only way I figured out how to do a rolling average that uses weights unique to each data point (rather than weights that remain the same for each window, which is possible using I thought something like the following might be available: result = da.weighted(month_weights).rolling(time = window_size).mean("time") but DataArrayWeighted does not have a "rolling" method. Is there any other way I can approach this? Thank you in advance for any help! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 9 replies
-
This would be great to have, but unfortunately it's not available in the default methods. Your approach seems reasonable! Possibly we could also compute the rolling sum of (values.weights), and divide by the rolling sum of weights... |
Beta Was this translation helpful? Give feedback.
-
The answer to not iterating over rolling and coarsen objects is usually This tutorial should be useful. |
Beta Was this translation helpful? Give feedback.
The answer to not iterating over rolling and coarsen objects is usually
rolling.construct
. This will give you a Xarray object with an "expanded" view of the data and then you can runweighted
on that.This tutorial should be useful.