我目前正在学习Pandas ,但遇到了一个问题.

我有以下数据:

labels = [ 'date', 'name', 'opponent', 'gf', 'ga']
data = [ 
 [ '2023-08-5', 'Liverpool', 'Man Utd', 5, 0 ],
 [ '2023-08-10', 'Liverpool', 'Everton', 0, 0 ],
 [ '2023-08-14', 'Liverpool', 'Tottenham', 3, 2 ],
 [ '2023-08-18', 'Liverpool', 'Arsenal', 4, 4 ],
 [ '2023-08-27', 'Liverpool', 'Man City', 0, 0 ],
]
df = pd.DataFrame(data, columns=labels)

游戏/行按日期排序.对于每一行/比赛,我想计算前一行/比赛中"goals_for"和"goals_against"的列值(不包括当前行或日期之后的行).

所以我希望数据是这样的:

labels = [ 'date', 'name', 'opponent', 'gf', 'ga', 'total_gf', 'total_ga' ]
data = [ 
 [ '2023-08-5', 'Liverpool', 'Man Utd', 5, 0, 0, 0 ],
 [ '2023-08-10', 'Liverpool', 'Everton', 0, 0, 5, 0 ],
 [ '2023-08-14', 'Liverpool', 'Tottenham', 3, 2, 5, 0 ],
 [ '2023-08-18', 'Liverpool', 'Arsenal', 4, 4, 8, 2 ],
 [ '2023-08-27', 'Liverpool', 'Man City', 0, 0, 12, 6 ],
]

我try 了expanding()个,但似乎包括当前行.rolling有参数closed='left',但其他人没有.

感谢任何帮助、提示或类似解决方案的链接.

推荐答案

您可以用fill_value=0shift,然后是cumsum:

df['total_gf'] = df['gf'].shift(fill_value=0).cumsum()
df['total_ga'] = df['ga'].shift(fill_value=0).cumsum()

或者,同时处理所有列:

df[['total_gf', 'total_ga']] = df[['gf', 'ga']].shift(fill_value=0).cumsum()

或者,创建一个新的数据框架:

out = df.join(df[['gf', 'ga']].shift(fill_value=0).cumsum().add_prefix('total_'))

输出:

         date       name   opponent  gf  ga  total_gf  total_ga
0   2023-08-5  Liverpool    Man Utd   5   0         0         0
1  2023-08-10  Liverpool    Everton   0   0         5         0
2  2023-08-14  Liverpool  Tottenham   3   2         5         0
3  2023-08-18  Liverpool    Arsenal   4   4         8         2
4  2023-08-27  Liverpool   Man City   0   0        12         6

Python相关问答推荐

如何在句子之间添加空白但忽略链接?

Gekko解算器错误results.json未找到,无法找出原因

为什么自定义pytree aux_data对于jnp.数组来说在.jit()之后跟踪,而对于np.数组来说则不是?

从多行文本中提取事件对

当pip为学校作业(job)安装sourcefender时,我没有收到匹配的分发错误.我已经try 过Python 3.8.10和3.10.11

Pandas 群内滚动总和

socket.gaierror:[Errno -2]名称或服务未知|Firebase x Raspberry Pi

如果AST请求默认受csref保护,那么在Django中使用@ system_decorator(csref_protect)的目的是什么?

如何使用Tkinter创建两个高度相同的框架(顶部和底部)?

在上下文管理器中更改异常类型

如何从FDaGrid实例中删除某些函数?

Locust请求中的Python和参数

如果条件为真,则Groupby.mean()

Select 用a和i标签包裹的复选框?

如何从具有不同len的列表字典中创建摘要表?

将输入管道传输到正在运行的Python脚本中

如何让Flask 中的请求标签发挥作用

图像 pyramid .难以创建所需的合成图像

在np数组上实现无重叠的二维滑动窗口

Stacked bar chart from billrame