作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有来自 kaggle 的 2018 年世界杯数据集。 World Cup Fifa statistics
在此数据集中,每一行代表的不是比赛,而是球队及其在比赛中的得分。
例如:
如何从此数据集中计算每个团队的净胜球数。我的意思是有没有更简单的方法或 Pandas 技巧。
我的计算是这样的:
goal_diff = {}
teams = df["Team"].unique()
for t in teams:
goal_diff[t] = df[df["Team"] == t]["Goal Scored"].sum() \
- df[df["Opponent"] == t]["Goal Scored"].sum()
感谢您的回复。
最佳答案
您可以通过 GroupBy.sum
进行聚合,减去并最后转换为 dict
:
goal_diff = ((df.groupby('Team')["Goal Scored"].sum() -
df.groupby('Opponent')["Goal Scored"].sum()).to_dict())
print (goal_diff)
{'Argentina': -3, 'Australia': -3, 'Belgium': 10,
'Brazil': 5, 'Colombia': 3, 'Costa Rica': -3,
'Croatia': 5, 'Denmark': 1, 'Egypt': -4,
'England': 4, 'France': 8, 'Germany': -2,
'Iceland': -3, 'Iran': 0, 'Japan': -1,
'Korea Republic': 0, 'Mexico': -3, 'Morocco': -2,
'Nigeria': -1, 'Panama': -9, 'Peru': 0,
'Poland': -3, 'Portugal': 0, 'Russia': 4,
'Saudi Arabia': -5, 'Senegal': 0, 'Serbia': -2,
'Spain': 1, 'Sweden': 2, 'Switzerland': 0,
'Tunisia': -3, 'Uruguay': 4}
关于python - Pandas 2018 世界杯数据集净胜球,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51514076/
我是一名优秀的程序员,十分优秀!