首页 > 解决方案 > 如何根据熊猫中的多列得出分数(排名)

问题描述

我有一个数据框如下:

User_ID Game_ID Liked   Shared  Category
1       11       Y       N      Music
1       11       Y       N      Music
1       22       Y       Y      Music
1       11       Y       N      Music
1       33       N       N      Dance
2       33       N       Y      Dance
2       44       Y       Y      Peace
2       11       N       N      Music

我需要Rating使用以下逻辑派生一个新列:

  1. 对于特定User_ID:如果对于特定Game_ID,两者LikedShared都是Ythen Score = 2,如果任何一个是Y,那么Score = 1,否则Score = 0
  2. 对于一个特定的User_ID:如果 aGame_ID重复超过 2 次,那么Score = 2,如果 2 次,那么1,否则Score = 0
  3. 对于特定的User_ID:如果 aGame_ID属于Category哪个是 Top Category Score = 1,否则Score = 0

    例如 : User_ID = 1, Top Category = Music(因为它的频率计数是 4 out 5),这个用户的所有Game_ID类别Music都将得到1.

    最后,我们需要每个User_ID-的累积分数Game_ID。例如:User_ID = 1Game_ID = 11

    1)喜欢/分享=任何一个是Y-Score = 1

    2)Category属于Game_ID该 User_ID 的顶级类别(音乐)所以Score : 1

    3)Game_ID为此重复两次以上User_ID-Score : 2 累积分数:1+1+2 = 4

以下是预期的输出:

User_ID Game_ID Like/Share  Category    Game_repeat Rating
      1      11          1         1              2      4
      1      22          2         1              0      3
      1      33          0         0              0      0
      2      33          1         0              0      1
      2      44          2         0              0      2
      2      11          0         0              0      0

注意:在预期的输出中,只有 User_ID、Game_ID 和 Rating 是至关重要的。其余列仅用于详细说明。

各位朋友能帮帮我吗?

标签: pythonpandasdataframe

解决方案


让我们试试这个:

df['Cond1'] = (df['Liked'] == 'Y').astype(int) + (df['Shared'] == 'Y').astype(int)

df['Cond2'] = df.groupby(['User_ID','Game_ID'])['Game_ID'].transform('size').sub(1).clip(0,2)

df['Cond3'] = df.groupby('User_ID')['Category'].apply(lambda x: ((x.value_counts().head(1).index[0] == x) & (x.value_counts().head(1).values[0] > 1).astype(int)))

df['Score'] = df['Cond1'] + df['Cond2'] + df['Cond3']

df_out = df.groupby(['User_ID','Game_ID'])['Score'].max().reset_index()

df_out

输出:

   User_ID  Game_ID  Score
0        1       11      4
1        1       22      3
2        1       33      0
3        2       11      0
4        2       33      1
5        2       44      2

推荐阅读