Calculating a value difference roughly week ago per group

Given your input dataframe:

df['date'] = pd.to_datetime(df['date']) #convert to datetime
df = df.sort_values(['group', 'date']).set_index('group') #sort by group and date
df['date_shifted'] = df.groupby(df.index)['date'].shift(1) #get date shifted within groups
df['date_diff'] = (df['date'] - df['date_shifted']).dt.days #calculate difference in days between current and previous dates
df['value_shifted'] = df.groupby(df.index)['value'].shift(1) #get value shifted within groups
df['diff'] = df.apply(lambda row: row['value']-row['value_shifted'] if 
(row['date_diff'] >=7) & (row['date_diff'] <=10) else np.nan, axis = 1) #calculate value difference if date difference satisfies [7,10] window

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top