添加每个用户的评分数列,熊猫

我正在使用表单的图书评级数据集


userID | ISBN | Rating

23413    1232     2.5

12321    2311     3.2

23413    2532     1.7

23413    7853     3.8

现在我需要添加第四列,其中包含每个用户在整个数据集中的评分数:


userID | ISBN | Rating | Ratings_per_user

23413    1232     2.5         3

12321    2311     3.2         1

23413    2532     1.7         3 

23413    7853     3.8         3

我努力了:


df_new['Ratings_per_user'] = df_new['userID'].value_counts()

但我收到一个错误:


A value is trying to be set on a copy of a slice from a DataFrame.

Try using .loc[row_indexer,col_indexer] = value instead

并且整个新列都填充了NaN.


千巷猫影
浏览 215回答 3
3回答

慕码人2483693

利用:df_new['Ratings_per_user']=df_new.groupby('userID')['userID'].transform('count')   userID  ISBN  rating  Ratings_per_user0   23413  1232     2.5                 31   12321  2311     3.2                 12   23413  2532     1.7                 33   23413  7853     3.8                 3

手掌心

将结果转换value_counts为dict,然后用于replace创建具有用户评分的新列x = df['userID'].value_counts().to_dict()df['rating_per_user'] = df['userID'].replace(x)print(df)输出:  userID  ISBN  rating  rating_per_user                                                                                              0   23413  1232     2.5                3                                                                                              1   12321  2311     3.2                1                                                                                              2   23413  2532     1.7                3                                                                                              3   23413  7853     3.8                3 

ibeautiful

你可以使用map:df['Rating per user'] = df['userID'].map(df.groupby('userID')['Rating'].count())print(df)   userID  ISBN  Rating  Rating per user0   23413  1232     2.5                31   12321  2311     3.2                12   23413  2532     1.7                33   23413  7853     3.8                3
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python