gpt4 book ai didi

python - pandas - 如何聚合两列并保留所有其他列

转载 作者:太空狗 更新时间:2023-10-30 02:30:11 25 4
gpt4 key购买 nike

我有以下 df 概要:

  movie id       movie title release date                                           IMDb URL                      genre  user id  rating  
0 2 GoldenEye (1995) 1-Jan-95 http://us.imdb.com/M/title-exact?GoldenEye%20(... Action|Adventure|Thriller 5 3
1 2 GoldenEye (1995) 1-Jan-95 http://us.imdb.com/M/title-exact?GoldenEye%20(... Action|Adventure|Thriller 268 2
2 2 GoldenEye (1995) 1-Jan-95 http://us.imdb.com/M/title-exact?GoldenEye%20(... Action|Adventure|Thriller 276 4
3 2 GoldenEye (1995) 1-Jan-95 http://us.imdb.com/M/title-exact?GoldenEye%20(... Action|Adventure|Thriller 217 3
4 2 GoldenEye (1995) 1-Jan-95 http://us.imdb.com/M/title-exact?GoldenEye%20(... Action|Adventure|Thriller 87 4

我正在寻找的是计算“用户 ID”和平均“评级”,并保持所有其他列完好无损。所以结果将是这样的:

  movie id       movie title release date                                           IMDb URL                      genre  user id     rating  
0 2 GoldenEye (1995) 1-Jan-95 http://us.imdb.com/M/title-exact?GoldenEye%20(... Action|Adventure|Thriller 50 3.75
1 3 Four Rooms (1995) 1-Jan-95 http://us.imdb.com/M/title-exact?GoldenEye%20(... Action|Adventure|Thriller 35 2.34

知道怎么做吗?

谢谢

最佳答案

如果您要聚合的列中的所有值对于每个组都是相同的,那么您可以通过将它们放入组中来避免连接。

然后将函数字典传递给agg。如果将 as_index 设置为 False 以将按列分组的内容保留为列:

df.groupby(['movie id','movie title','release date','IMDb URL','genre'], as_index=False).agg({'user id':len,'rating':'mean'})

注意len是用来计数的

关于python - pandas - 如何聚合两列并保留所有其他列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28505675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com