'how to iterate and sum previous values over especific index with pandas

i'm a new in the programming world so, i have a question about a dataframe and iteration problem. (i'm using python)

i have the follow:

this is my dataframe

in the first column (x) i have the date and in the second column (y), i have some values (the total shape is (119,2))

my question is:

if i want to select the date "2020-12-01" and sum the 14 previous values and asing this result to this date and do the same for the next date, how can i do that ?

(i put the blue color over the date, and red over the values that i want to add to blue value, in the previous image )

i tried to do the follow:

  final_value = 0
  for i in data["col_name"]:
    final_value = data["col_name"].iloc[i:14].sum()  

but the output is 0.

so, can someone give me some ideas to solve it problem?

thanks to read me



Solution 1:[1]

Convert x column time to datetime

df['x'] = pd.to_datetime(df['x'], format='%Y-%m-%d')

Use rolling to select 14 days to add up

df.rolling("14D", on="x").sum()['y']

Try this on your full dataset

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pyaj