Home > Enterprise >  Create some features based on the mean of y for the month over the past few years
Create some features based on the mean of y for the month over the past few years

Time:10-17

Assuming we have dataset df (which can be downloaded from enter image description here

df.head(10)

Out:

enter image description here

Reference:

Pandas, how to calculate mean values of the past n years for every month

CodePudding user response:

You can construct the shifted columns in a separate object so you don't have to drop from the dataframe after. Combine that with loops for conciseness:

shifted = np.array([df["y"].shift(i) for i in [12, 24, 36]]).T
for i in range(2, 4):
    df[f"y_avg_last{i}"] = shifted[:, :i].mean(axis=1)
  • Related