【发布时间】:2020-09-22 18:25:56
【问题描述】:
我正在尝试对 last_n 行的列执行滚动求和,并转换为数据框中的新列,并按不同的列分组。所以这是我拥有的数据框类型的示例:
id. a. b. c. date.
01 0 abc def 1/22/20
01 2 abc def 1/23/20
01 1 abc def 1/24/20
01 1 abc def 1/25/20
02 4 abc def 1/22/20
02 5 abc def 1/23/20
02 5 abc def 1/24/20
02 0 abc def 1/25/20
03 1 abc def 1/22/20
03 0 abc def 1/23/20
03 2 abc def 1/24/20
03 2 abc def 1/25/20
.
.
.
这些是任意值,但假设我想对每个id 在column=a. 的过去 2(示例)天进行滚动求和。输出应如下所示:
如果过去的 n 天不存在,只需将 0 添加到累计总和中。
id. a. b. c. date. rolling_2_a
01 0 abc def 1/22/20 0
01 2 abc def 1/23/20 2
01 1 abc def 1/24/20 3
01 1 abc def 1/25/20 2
02 4 abc def 1/22/20 4
02 5 abc def 1/23/20 9
02 5 abc def 1/24/20 10
02 0 abc def 1/25/20 5
03 1 abc def 1/22/20 1
03 0 abc def 1/23/20 1
03 2 abc def 1/24/20 2
03 2 abc def 1/25/20 4
.
.
.
我知道如何根据 id 进行求和,但在这里使用日期元素 + last_n 要求,我不确定 pandas 是否具有该功能。
为此,我们假设date 列也可能未排序,但两者的示例将不胜感激。
【问题讨论】:
标签: python pandas dataframe group-by sum