numpy中的groupby,计数和平均值,python中的pandas

Ana*_*d T 5 numpy python-3.x pandas jupyter

我有一个看起来像这样的数据框:

       userId  movieId  rating
0           1       31     2.5
1           1     1029     3.0
2           1     3671     3.0
3           2       10     4.0
4           2       17     5.0
5           3       60     3.0
6           3      110     4.0
7           3      247     3.5
8           4       10     4.0
9           4      112     5.0
10          5        3     4.0
11          5       39     4.0
12          5      104     4.0
Run Code Online (Sandbox Code Playgroud)

我需要获取一个数据框,它具有唯一的 userId、用户的评分数和用户的平均评分,如下所示:

       userId    count    mean
0           1        3    2.83
1           2        2     4.5
2           3        3     3.5
3           4        2     4.5
4           5        3     4.0
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

Sco*_*ton 6

df1 = df.groupby('userId')['rating'].agg(['count','mean']).reset_index()
print(df1)


   userId  count      mean
0       1      3  2.833333
1       2      2  4.500000
2       3      3  3.500000
3       4      2  4.500000
4       5      3  4.000000
Run Code Online (Sandbox Code Playgroud)


Kew*_*ewl 5

删除,movieId因为我们没有使用它 groupby userId,然后应用聚合方法:

import pandas as pd

df = pd.DataFrame({'userId': [1,1,1,2,2,3,3,3,4,4,5,5,5],
                  'movieId':[31,1029,3671,10,17,60,110,247,10,112,3,39,104],
                  'rating':[2.5,3.0,3.0,4.0,5.0,3.0,4.0,3.5,4.0,5.0,4.0,4.0,4.0]})

df = df.drop('movieId', axis=1).groupby('userId').agg(['count','mean'])

print(df)
Run Code Online (Sandbox Code Playgroud)

其中产生:

       rating          
        count      mean
userId                 
1           3  2.833333
2           2  4.500000
3           3  3.500000
4           2  4.500000
5           3  4.000000
Run Code Online (Sandbox Code Playgroud)