我目前正在学习 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 ],
]
我尝试了
expanding()
,但它似乎包括当前行。 rolling
有参数closed='left'
但其他没有。
任何帮助或提示或类似解决方案的链接将不胜感激。
IIUC 你可以做:
df["total_gf"] = df["gf"].shift(fill_value=0).cumsum()
df["total_ga"] = df["ga"].shift(fill_value=0).cumsum()
print(df)
打印:
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
shift
与 fill_value=0
,然后 cumsum
:
df['total_gf'] = df['gf'].shift(fill_value=0).cumsum()
df['total_ga'] = df['ga'].shift(fill_value=0).cumsum()
输出:
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