Python 如何从panda数据帧返回单个组
我有一个数据框,里面有得分者,我想把得分最高的小组抽取成一个数组。该组可以包含多个项目(在下面的示例中,有两名球员有8个目标) 因此,在下面的示例中,它将生成如下数组:Python 如何从panda数据帧返回单个组,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我有一个数据框,里面有得分者,我想把得分最高的小组抽取成一个数组。该组可以包含多个项目(在下面的示例中,有两名球员有8个目标) 因此,在下面的示例中,它将生成如下数组: [{'goals': 8, 'name': 'Sergio Agüero', 'team': 'Manchester City'}, {'goals': 8, 'name': 'Tammy Abraham', 'team': 'Chelsea'}] top\u scoring\u group=top\u scorers.gr
[{'goals': 8, 'name': 'Sergio Agüero', 'team': 'Manchester City'}, {'goals': 8, 'name': 'Tammy Abraham', 'team': 'Chelsea'}]
top\u scoring\u group=top\u scorers.groupby(“team”,as\u index=False)['goals'].sum().nlagest(1,'goals',keep='all')['team']
这将获得目标最多的团队,如果有多个,则保留所有目标。top\u scoring\u group=top\u scorers.groupby(“团队”,如'u index=False)['goals'].sum().nlagest(1,'goals',keep='all')['team']
这将获得目标最多的团队,如果有多个目标,则保留所有目标。IIUC
(top_scorers[top_scorers['goals'].eq(top_scorers['goals'].max())]
.to_dict('rows')
)
输出:
[{'name': 'Sergio Agüero', 'team': 'Manchester City', 'goals': '8'},
{'name': 'Tammy Abraham', 'team': 'Chelsea', 'goals': '8'}]
IIUC
输出:
[{'name': 'Sergio Agüero', 'team': 'Manchester City', 'goals': '8'},
{'name': 'Tammy Abraham', 'team': 'Chelsea', 'goals': '8'}]
我得到了这个错误:ValueError:keep必须是“first”、“last”并且,groupby应该是目标,而不是团队。如果最终结果是如问题开头所示的数组,那就太好了。对于pandas v0.25.2,keep必须是{'first','last','all',默认值为'first'。对于groupby,我误解了你的问题。我得到了一个错误:ValueError:keep必须是“first”,“last”,而且groupby应该是目标,而不是团队。如果最终结果是如问题开头所示的数组,那就太好了。对于pandas v0.25.2,keep必须是{'first','last','all',默认值为'first'。对于groupby,我误解了你的问题。