Rolling Sum with conditions

Asked

Viewed 18 times

0

I have the following dataframe

data = data = [['1996-01-10', 10, 0], ['1996-01-10', 5, 0], ['1996-01-11', 4, 1], ['1996-01-13', 14, 1],
               ['1996-01-13', 1, 0], ['1996-01-13', 13, 0], ['1996-01-16', 25, 0], ['1996-01-18', 9, 0],
               ['1996-01-20', 47, 1], ['1996-01-20', 10, 1], ['1996-01-21', 5,1], ['1996-01-22', 8, 1]]
    
df = pd.DataFrame(data, columns = ['Date', 'Value', 'Dummy']) 

My problem is this: I want to make a sum, but it obeys some conditions. That is, if the value of 'Dummy' == 1, then I want to add the 'Value' of the last three days, but only for the observations that have 'Dummy' == 0.

The solution in this case would be:

data = [['1996-01-10', 10, 0, 0], ['1996-01-10', 5, 0, 0], ['1996-01-11', 4, 1, 15], ['1996-01-13', 14, 1, 15],
               ['1996-01-13', 1, 0, 0], ['1996-01-13', 13, 0, 0], ['1996-01-16', 25, 0, 0], ['1996-01-18', 9, 0, 0],
               ['1996-01-20', 47, 1, 9], ['1996-01-20', 10, 1, 9], ['1996-01-21', 5, 1, 9], ['1996-01-22', 8, 1, 0]]
    
df2 = pd.DataFrame(data, columns = ['Date', 'Value', 'Dummy', 'Soma']) 

In the background I first want to see if the 'Dummy' is equal to 1 and then sum all the values of the last 3 days that have 'Dummy' equal to 0.

Thank you!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.