0

I have a DataFrame with monthly data that looks something like this:

id date window_in_months value
1 2000-01-01 3 20
1 2000-02-01 3 30
2 2000-01-01 12 40
2 2000-02-01 12 60

I want to do a rolling groupby but use the value in column window_in_months as the window parameter. I can use a static window by just doing:

df.groupby('id')['value'].rolling(window=3, min_periods=3)

But I can't figure out how to have the window and min_periods change with the group under consideration. The window_in_months will always be the same for all ids that are the same.

2
  • I'm not sure what to do with this. Is the sample input even enough to evaluate the window? The window size is 3 or 12, but the groups are only ever size 2. Commented Jul 21 at 22:39
  • There are more rows, this is just an illustrative example. Think a couple thousand rows with about 50 ids and various month end dates per id. Commented Jul 22 at 13:35

1 Answer 1

0

I think I figured it out:

def dynamic_rolling_window(group):
    window = group['window_in_months'].iloc[0] # we now have the window in a variable
    return group['value'].rolling(window=window, min_periods=window).apply(some_other_function)

df['rolling_value'] = df.groupby('id', group_keys=False).apply(dynamic_rolling_window)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.