0

I'm trying to calculate a 3 month weighted average.

I can perform a simple average, like so:

df.rolling(3)['B'].mean()

However when I pass in a custom function to get a weighted average :

df.rolling(3).apply(lambda x: sum(x['A'] * x['B']) / sum(x['A']),raw='false')

I'm expecting the rolling function to first set the scope of the operation, then then the function to be applied to said scope. However, I'm getting an 'IndexError'

Any ideas on how to resolve (and why conceptually, this doesn't work)?

jedd
  • 420
  • 1
  • 6
  • 13
  • 2
    You're getting an IndexError because your custom function is applied to each column in the input dataframe separately. That means when you try to access `x['a']` or `x['b']`, each column is being indexed itself, not the dataframe. Ideally, your rolling function would be applied to the dataframe as a whole, but I don't know if that is cleanly possible. Perhaps this will work? `(df["A"] * df["B"]).rolling(3).sum() / df["A"].rolling(3).sum()` – Chrysophylaxs Mar 17 '23 at 12:03

0 Answers0