1 回答
TA贡献1803条经验 获得超6个赞
改进了之前的答案并设法解决了 groupby 的排序问题
df = pd.read_csv("data.csv")
df["Date"] = pd.to_datetime(df['Date'], format='%m-%d-%y')
df["CurrentWon"] = df["Prize"] * df["IfWon"]
result = df.groupby("ID").rolling("7D", on = 'Date', closed = 'right').CurrentWon.sum().reset_index()
result.rename(columns={"CurrentWon": "PreviousWon"}, inplace=True)
df = df.merge(result, on=["ID", "Date"])
df["PreviousWon"] -= df["CurrentWon"]
print(df)
输出:
ID Date Prize IfWon CurrentWon PreviousWon
0 1 2020-01-01 5 1 5 0.0
1 2 2020-01-01 8 1 8 0.0
2 1 2020-01-03 3 0 0 5.0
3 1 2020-01-04 10 1 10 5.0
4 1 2020-01-07 5 0 0 15.0
5 2 2020-01-10 5 1 5 0.0
6 3 2020-01-10 10 1 10 0.0
添加回答
举报