我有以下数据帧:
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
提前谢谢
让我们计算
level=0
上的mean
,然后map
计算出的平均值到Name
列以广播聚合结果如果我们需要在多个列上
group
例如Name
和City
,那么我们必须在level=[Name, City]
和map
上使用MultiIndex.map
计算出的平均值使用自定义lambda函数的
groupby
和transform
的替代方法相关问题 更多 >
编程相关推荐