从 pandas 数据框中的类别(列)中选择前 n 行并对其执行计算

Gok*_*lai 3 dataframe python-3.x pandas

我是 pandas 的新手,我正在分析 FIFA 数据集,我需要为每个位置选择前 5 名球员(基于总分)。

还,

我想检查是否有任何球员出现在多个小组中,是否存在上述情况。2. 对各个组进行均值、最大值等运算。

谢谢

当我使用此操作时,我无法检索其他列,例如姓名和工资。

fifa_df.groupby('Position')['Overall'].nlargest(5).groupby('Position').head()

样本数据: 在此输入图像描述 预期结果如下:

在此输入图像描述

我还试图找到不止一组中的所有玩家,

并尝试对每个位置前5名的球员进行平均工资等操作。

数据集链接 - fifa_dataset

taw*_*eel 5

尝试在 apply 中使用 nlargest

\n\n
res = df[['Name','Position','Overall','Wage']]\nres= res.groupby(['Position'],as_index=False).apply(lambda x: x.nlargest(5, 'Overall'))\nres.reset_index(inplace=True)\ndata.drop(['level_0','level_1'],axis=1,inplace=True)\nprint(data)\n
Run Code Online (Sandbox Code Playgroud)\n\n
    Name       Position Overall Wage\n0   A. Griezmann    CAM 89     \xe2\x82\xac145K\n1   C. Eriksen      CAM 88     \xe2\x82\xac205K\n2   Roberto Firmino CAM 86     \xe2\x82\xac195K\n3   T. M\xc3\xbcller       CAM 86     \xe2\x82\xac135K\n4   M. \xc3\x96zil         CAM 86     \xe2\x82\xac190K\n5   D. God\xc3\xadn        CB  90     \xe2\x82\xac125K\n6   S. Umtiti       CB  87     \xe2\x82\xac205K\n7   M. Benatia      CB  86     \xe2\x82\xac160K\n8   N. Otamendi     CB  85     \xe2\x82\xac170K\n9   Naldo           CB  85     \xe2\x82\xac38K\n....\n
Run Code Online (Sandbox Code Playgroud)\n\n

我希望它能解决你的问题

\n