SHV_la
SHV_la

Reputation: 987

Sum of quantity over several days prior to day of interest

I have a dataframe of flood size (0 [no flood] to 3 [large flood]) and precipitation on daily timescale. This is a snippet of the data:

     date       Size    ppt
2017-09-13      0.0     0.000000
2017-09-14      0.0     34.709998
2017-09-15      0.0     0.000000
2017-09-16      0.0     0.000000
2017-09-17      0.0     0.000000
2017-09-18      0.0     0.600000
2017-09-19      3.0     157.439998

I am interested in how much rainfall falls in 'X' number of days prior to the flood, not just the amount of rain that falls on the day of the flood. For example, using the data above, over the seven days prior to the flood on 2017-09-19, ~193mm fell, and in the preceding three days ~158mm fell. However, I have no idea how to code this. Can anyone out there help?

Thank you :)

Upvotes: 0

Views: 96

Answers (1)

Vishnu Kunchur
Vishnu Kunchur

Reputation: 1726

I'm guessing you are only concerned with rows where there was a flood, i.e. Size != 0. You could filter out those rows after applying the code below.

Given a DataFrame rain as follows:

     date       Size    ppt
2017-09-13      0.0     0.000000
2017-09-14      0.0     34.709998
2017-09-15      0.0     0.000000
2017-09-16      0.0     0.000000
2017-09-17      0.0     0.000000
2017-09-18      0.0     0.600000
2017-09-19      3.0     157.439998


## 7-day cumulative precipitation
rain['ppt_7day'] = rain['ppt'].rolling(7).sum()
## 3-day cumulative precipitation
rain['ppt_3day'] = rain['ppt'].rolling(3).sum()

Output:

          date size     ppt    ppt_7day    ppt_3day
0  2017-09-13     0       0         NaN         NaN
1   2017-09-14    0   34.71         NaN         NaN
2   2017-09-15    0       0         NaN   34.709998
3   2017-09-16    0       0         NaN   34.709998
4   2017-09-17    0       0         NaN    0.000000
5   2017-09-18    0     0.6         NaN    0.600000
6   2017-09-19    3  157.43  192.739998  158.030000

Upvotes: 2

Related Questions