python-如何找到最大的熊猫群

时间:2018-12-21 10:38:38

标签: python python-3.x pandas

我有一个评级数据框,其中包含userId, movieId, rating行。我想找到评分最高的用户。

这是我编写的代码:

import pandas as pd
ratings = pd.read_csv('ratings.csv') # userId,movieId,rating
user_rating_counts = ratings[['userId','movieId']].groupby('userId')['movieId'].agg(['count'])
top_rator = user_rating_counts[user_rating_counts['count']==user_rating_counts['count'].max()]

文件的外观如下:

userId,movieId,rating
1,1,4.0
1,3,4.0
1,6,4.0
1,47,5.0
1,50,5.0
1,70,3.0
1,101,5.0
1,110,4.0

当我在jupyter笔记本中查看top_rator时,它看起来像这样:

       count
userId  
414     2698

我想从中得到一个元组,例如:

(414, 2698)

我该怎么做?

P.S。关于如何更好/更快/更短地完成此操作的任何评论将不胜感激。

3 个答案:

答案 0 :(得分:2)

您可以这样做:

sizes = df.groupby(['userId']).size()
(sizes.idxmax(), sizes.max())
#(1, 8)

详细信息

userId分组,并获取每个组的size

sizes = df.groupby(['userId']).size()
#userId
#1    8
#2    1

使用idxmaxmax创建具有最高评分数的用户元组:

(sizes.idxmax(), sizes.max())
#(1, 8)

答案 1 :(得分:2)

如果只有一个用户匹配max,则可以简单地使用:

next(top_rator.max(1).items())

说明

top_rator.max(1)将返回:

userId
1    8
dtype: int64

Series.items()延迟迭代该系列,在tuple生成器对象中创建索引和值的zip

next()用于访问此生成器中的“下一个”(第一个)tuple


如果有多个与最大匹配的用户,请使用列表理解:

[(idx, val) for idx, val in top_rator.max(1).items()]

答案 2 :(得分:2)

在列表中将groupbysize一起使用,然后将Series.aggmaxidxmax一起使用:

tup = tuple(ratings.groupby('userId').size().agg(['idxmax','max']))
print (tup)
(1, 8)

说明

每个组的首个汇总size

#changed data - multiple groups
print (df)
   userId  movieId  rating
0       1        1     4.0
1       1        3     4.0
2       1        6     4.0
3       2       47     5.0
4       2       50     5.0
5       2       70     3.0
6       2      101     5.0
7       3      110     4.0

print (df.groupby('userId').size())
userId
1    3
2    4
3    1
dtype: int64

输出为Series,因此在Series.agg中添加了功能列表idxmaxmax的索引,并为Series的值提供了最大值:

print (df.groupby('userId').size().agg(['idxmax','max']))
idxmax    2
max       4
dtype: int64

最后转换为tuple

print (tuple(df.groupby('userId').size().agg(['idxmax','max'])))
(2, 4)

多个具有相同最大大小的组的解决方案:

print (ratings)   
   userId  movieId  rating
0       1        1     4.0
1       1        3     4.0
2       1        6     4.0
3       2       47     5.0
4       2       50     5.0
5       2       70     3.0
6       3      101     5.0
7       3      110     4.0

每个组首先聚合size,但是有2个组的最大3值:

user_rating_counts = ratings.groupby('userId')['movieId'].size()
print (user_rating_counts)
userId
1    3
2    3
3    2
Name: movieId, dtype: int64

因此,请首先使用boolean indexing

top_rator = (user_rating_counts[user_rating_counts == user_rating_counts.max()])
print (top_rator)
userId
1    3
2    3
Name: movieId, dtype: int64

创建DataFrame并转换为元组列表:

tup = list(map(tuple, top_rator.reset_index().values.tolist()))
print (tup)
[(1, 3), (2, 3)]