选择pandas groupby中的前n项并计算平均值

2024-10-01 02:37:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

df = pd.DataFrame({'Value': [0, 1, 2,3, 4,5,6,7,8,9],'Name': ['John', 'Jim', 'John','Jim', 'John','Jim','Jim','John','Jim','John']})
df
    Value   Name
0   0   John
1   1   Jim
2   2   John
3   3   Jim
4   4   John
5   5   Jim
6   6   Jim
7   7   John
8   8   Jim
9   9   John

我想通过Name选择顶部的n项,并从Value列中找到平均值

我试过这个:

df['Top2Mean'] = df.groupby(['Name'])['Value'].nlargest(2).transform('mean')

但有以下错误:

ValueError: transforms cannot produce aggregated results

我的预期结果是一个名为Top2Mean的新列,在John旁边有一个8,在Jim旁边有一个7

提前谢谢


Tags: 数据namedataframedfvalue错误transformmean
1条回答
网友
1楼 · 发布于 2024-10-01 02:37:12

让我们计算level=0上的mean,然后map计算出的平均值到Name列以广播聚合结果

top2 = df.groupby('Name')['Value'].nlargest(2).mean(level=0)
df['Top2Mean'] = df['Name'].map(top2)

如果我们需要在多个列上group例如NameCity,那么我们必须在level=[Name, City]map上使用MultiIndex.map计算出的平均值

c = ['Name', 'City']
top2 = df.groupby(c)['Value'].nlargest(2).mean(level=c)
df['Top2Mean'] = df.set_index(c).index.map(top2)

使用自定义lambda函数的groupbytransform的替代方法

df['Top2Mean'] = df.groupby('Name')['Value']\
                   .transform(lambda v: v.nlargest(2).mean())

   Value  Name  Top2Mean
0      0  John         8
1      1   Jim         7
2      2  John         8
3      3   Jim         7
4      4  John         8
5      5   Jim         7
6      6   Jim         7
7      7  John         8
8      8   Jim         7
9      9  John         8

相关问题 更多 >