计算熊猫的n日增长率

时间:2020-09-09 05:49:33

标签: python pandas

我有一个如下数据框:

'country_code', 'count_date', 'case_count'
CAN           ,  2020-09-01 ,  1700000
CAN           ,  2020-08-31 ,  1650000
...           ,  ....       ,  ....
SGP           ,  ....       ,  ....
...           ,  ....       ,  ....
USA           ,  ....       ,  ....
...           ,  ....       ,  ....

其排序为:

df = df.sort_values(['country_code','count_date'], ascending=[True,False])

假设f(x)是第x天的case_count,那么我需要计算:

(f(x) - f(x-7))/(f(x-8) - f(x-15)

每个国家/地区代码

我可以如下计算连续日期之间的差异:

df['dailynew_cases'] = df.groupby('country_code')['case_count'].diff(-1)

但是如何计算7天(或n天)的增长率并将其保存在同一DF中的另一列?

编辑#1: pct_change函数与所需的输出不匹配。以下是美国在2020-08-29的值

case_count = [5867633.0, 5573695.0, 5529672.0, 5248806.0] 
count_date = [datetime.date(2020, 8, 28), datetime.date(2020, 8, 21), datetime.date(2020, 8, 20), datetime.date(2020, 8, 14)]

所需的输出为(5867633.0-5573695.0)/(5529672.0-5248806.0) = 1.0465 但是pct_change给出0.0518

2 个答案:

答案 0 :(得分:1)

要获取增长率,可以使用pct_change

df['growth'] =  df.groupby('country_code')['case_count'].pct_change(periods=7)

答案 1 :(得分:0)

我可以使用shift

解决此问题
df['growth_rate'] = df.groupby('country_code').case_count.transform(lambda x: (x.shift(-1) - x.shift(-n)) / (x.shift(-n-1) - x.shift(-n-n))*100)