Calculate the sum of values based off specified range in a Dataframe

Viewed 46

I have a set of data (df) that I need to refine, It shows the daily rainfall average for 20 years, my goal is, to sum up, the average rainfall for every rainy season which is from October 1st to May 31st the following year. I had initially filtered the data to only contain average for the rain season and I was even able to calculate the total for every season by using a step value of 242 since the interval between 1st October and 31st May is 242 days apart, df.groupby(np.arange(len(df)) // 242).sum(). But then I did not consider leap years which have an additional day. I need to find a way to specify the range. Please help!

1 Answers

If you have datetimes, you can filter your dataframe to only include the months October to May:

df['Date'] = pd.to_datetime(df['Date']) 
df = df[df['Date'].dt.month < 6 or dt.month > 9 ]

From there you can use Grouper to group by and sum the 8 months, be sure dataset starts on October:

df.groupby(pd.Grouper('8M')).sum()

Hope that works :)

Related