Created
July 30, 2020 15:23
-
-
Save smowton/06d0284ae6ca5650b6d07947620e56eb to your computer and use it in GitHub Desktop.
Python to add 7-day rolling sum to a CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import datetime | |
import sys | |
# Adds a 7-day rolling sum to a CSV | |
# Input: date,cases | |
# date format: yyyy-mm-dd | |
# Output: date,cases,last7days | |
recs = [] | |
for rec in sys.stdin: | |
rec = rec.strip().split(",") | |
if len(rec) == 0: | |
continue | |
assert len(rec) == 2 | |
date = datetime.datetime.strptime(rec[0], '%Y-%m-%d') | |
count = int(rec[1]) | |
recs.append((rec[0], date, count)) | |
def last_7_days(end): | |
start = end - datetime.timedelta(6) | |
return sum(rec[2] for rec in recs if rec[1] <= end and rec[1] >= start) | |
for rec in recs: | |
print ",".join([rec[0], str(rec[2]), str(last_7_days(rec[1]))]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment