python - 如何根据熊猫中的多列得出分数(排名)
问题描述
我有一个数据框如下:
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
使用以下逻辑派生一个新列:
- 对于特定
User_ID
:如果对于特定Game_ID
,两者Liked
和Shared
都是Y
thenScore = 2
,如果任何一个是Y
,那么Score = 1
,否则Score = 0
。 - 对于一个特定的
User_ID
:如果 aGame_ID
重复超过 2 次,那么Score = 2
,如果 2 次,那么1
,否则Score = 0
。 对于特定的
User_ID
:如果 aGame_ID
属于Category
哪个是 Top CategoryScore = 1
,否则Score = 0
例如 :
User_ID = 1
,Top Category = Music
(因为它的频率计数是 4 out 5),这个用户的所有Game_ID
类别Music
都将得到1
.最后,我们需要每个
User_ID
-的累积分数Game_ID
。例如:User_ID = 1
,Game_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 是至关重要的。其余列仅用于详细说明。
各位朋友能帮帮我吗?
解决方案
让我们试试这个:
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
推荐阅读
- javascript - React:我可以返回之前渲染的结果吗?
- c# - 如何在c#中创建一个多折线图
- api - 无法通过 API 将测试运行状态更新为已完成
- sql - 无法在 SQL Server 中创建没有 Azure 订阅的 SSIS DB
- c# - 如何通过拆分列将 3 个列表添加到一个 ListView 中
- angular - 在 Angular 7 中提供服务别名会中断构建执行
- python - 运行时如何从代码中删除 \n,
- string - 表示一定数量的字符串所需的 trie 节点数
- javascript - 带有点击事件的条件是否适用于否定语句?
- r - 创造在梦幻足球联赛中获胜的累积概率