I have a pandas dataset with multiple columns of data as follows:
code country_region date retail transit work res
CA Canada 2020-02-15 4 3 1 0
CA Canada 2020-02-16 13 4 0 -2
CA Canada 2020-02-17 -12 -28 -52 11
CA Canada 2020-02-18 -1 -1 -1 1
CA Canada 2020-02-19 1 0 0 0
CA Canada 2020-02-20 6 -1 1 0
CA Canada 2020-02-21 2 -1 -3 1
CA Canada 2020-02-22 8 6 6 -1
CA Canada 2020-02-23 7 -5 5 6
...
US United States 2020-02-15 6 3 1 0
US United States 2020-02-16 13 4 0 -2
...
My objective is to calculate a 7 day average for each of the numeric values within each code / country_region value (I have confirmed there are no missing dates in the data). This would be quite easy in Excel using a ranged average, but unfortunately my table has a very high number of records.
I would also first need to convert my date field to a date object since the date is text. I could perform this utilizing a loop, but it seems unwieldy to retain the "last 6 days" for each of the numeric columns. I have seen the df.rolling() function, but there are few examples of this applied with a group_by statement, and few examples with multiple columns. Is there a python (i.e. non-looped) way to perform this summation?
Edit: I've converted the date column to a proper date field using:
df['date_fmt'] = pd.to_datetime(df['date']).apply(lambda t: datetime.datetime.fromisoformat(str(t)))