我有一个数据帧df,如下所示:
country_code count_date confirmed_cases
0 AFG 2020-09-13 38641.0
1 AFG 2020-09-12 38606.0
2 AFG 2020-09-11 38572.0
3 AFG 2020-09-10 38544.0
4 AFG 2020-09-09 38520.0
... ... ... ...
19521 ZWE 2020-06-03 206.0
19522 ZWE 2020-06-02 203.0
19523 ZWE 2020-06-01 178.0
19524 ZWE 2020-05-31 174.0
19525 ZWE 2020-05-30 149.0
groupby country_code之后,如何创建一个新列,该列的每个日期的Confirmed_cases减去n天前的Confirmed_cases。
我尝试过
n = 7
df.groupby('country_code').confirmed_cases.transform(lambda x:x-x.iloc[::n])
不起作用。
答案 0 :(得分:1)
您可以执行shift
n = 7
out = df['confirmed_cases'] - df.groupby('country_code').confirmed_cases.shift(n)
更新:
df.groupby('country_code').confirmed_cases.apply(lambda x:x-x.shift(n))