Вот подход с defaultdict
import csv
from collections import defaultdict
from datetime import datetime
path = "C:\\Users\\USER\\Desktop\\YOUR_FILE_HERE.csv"
with open(path, "r") as f:
d = defaultdict(int)
rows = csv.reader(f)
for dte, followers in rows:
dte = datetime.strptime(dte, "%Y-%m-%d")
d[dte.year, dte.month] += int(followers)
print d
to_date_followers = 0
for (year, month) in sorted(d):
last_month_and_year = (12, year-1) if month == 1 else (month-1, year)
old_followers = d.get(last_month_and_year, 0)
new_followers = d[year, month]
to_date_followers += new_followers
print "%d followers gained in %s, %s resulting in a %.2f%% increase from %s (%s followers to date)" % (
new_followers-old_followers, month, year, new_followers*100.0/to_date_followers, ', '.join(str(x) for x in last_month_and_year), to_date_followers
)
Для входа ниже:
2015-12-05,10
2015-12-31,10
2016-01-01,105
2016-02-08,195
2016-03-01,200
2016-03-10,200
2017-03-01,200
Он печатает:
defaultdict(<type 'int'>, {(2015, 12): 20, (2016, 1): 105, (2016, 3): 400,
(2017, 3): 200, (2016, 2): 195})
20 followers gained in 12, 2015 resulting in a 100.00% increase from 11, 2015 (20 followers to date)
105 followers gained in 1, 2016 resulting in a 84.00% increase from 12, 2015 (125 followers to date)
195 followers gained in 2, 2016 resulting in a 60.94% increase from 1, 2016 (320 followers to date)
400 followers gained in 3, 2016 resulting in a 55.56% increase from 2, 2016 (720 followers to date)
200 followers gained in 3, 2017 resulting in a 21.74% increase from 2, 2017 (920 followers to date)
Может ли вы дать нам пример ввод и вывод образца (в формате CSV)? – Bahrom
'm = (y2 - y1)/(x2 - x1)', так что бы вы просто не делали «rate = (followers - prev_fol)/(time-prev_time)»? Это будет означать изменение сторонников в отношении изменения времени для любого временного интервала –
Я думаю, что это действительно зависит от того, что означает, что это будет темп роста «месяц за месяцем». Предположительно, вы хотите мгновенный темп роста, нормированный на какой-то 30-дневный месяц? – Paul