如何基于多变量对独热编码的影视评分数据进行分组排序?
问题描述
我有如下带评分的影视节目数据,已按节目类型完成独热编码(值为0或1):
| show | review score | Action & Adventure | Anime Features | Anime Series | British TV Shows | Children & Family Movies |
|---|---|---|---|---|---|---|
| a | 8 | 1 | 0 | 0 | 0 | 0 |
| b | 10 | 0 | 1 | 0 | 0 | 0 |
| c | 9 | 0 | 1 | 0 | 0 | 0 |
| d | 6 | 0 | 0 | 1 | 0 | 0 |
| e | 9 | 0 | 0 | 0 | 1 | 0 |
| f | 7 | 0 | 0 | 0 | 0 | 1 |
| g | 8 | 0 | 0 | 0 | 0 | 1 |
| h | 8 | 1 | 0 | 0 | 0 | 0 |
希望按以下规则处理数据:以类型为首要分组依据,评分按降序排列,同时统计对应评分的节目数量,得到如下格式结果:
| genre | review score | count |
|---|---|---|
| Action & Adventure | 8 | 2 |
| Anime Features | 10 | 1 |
| 9 | 1 | |
| Anime Series | 6 | 1 |
| British TV Shows | 9 | 1 |
| Children & Family Movies | 8 | 1 |
| 7 | 1 |
尝试过groupby方法,但因涉及列数较多难以实现,寻求可行解决方案。
解决方案
可以通过重塑数据结构的方式简化处理,用Pandas的melt方法把独热编码的类型列转换为长格式,再进行分组统计:
import pandas as pd # 构造原始数据 data = { 'show': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], 'review score': [8, 10, 9, 6, 9, 7, 8, 8], 'Action & Adventure': [1, 0, 0, 0, 0, 0, 0, 1], 'Anime Features': [0, 1, 1, 0, 0, 0, 0, 0], 'Anime Series': [0, 0, 0, 1, 0, 0, 0, 0], 'British TV Shows': [0, 0, 0, 0, 1, 0, 0, 0], 'Children & Family Movies': [0, 0, 0, 0, 0, 1, 1, 0] } df = pd.DataFrame(data) # 1. 重塑数据:将独热编码的类型列转为长格式,筛选出值为1的行(即节目所属的类型) melted_df = df.melt( id_vars=['show', 'review score'], var_name='genre', value_name='is_genre' ).query('is_genre == 1').drop(columns='is_genre') # 2. 按类型和评分分组,统计数量,同时按类型分组内评分降序排列 result = melted_df.groupby(['genre', 'review score'], as_index=False).size() result = result.rename(columns={'size': 'count'}).sort_values(by=['genre', 'review score'], ascending=[True, False]) # 3. 处理genre列的重复值,只保留每组的第一个值 result['genre'] = result['genre'].mask(result['genre'].duplicated(), '') print(result)
代码解释
melt重塑数据:把宽格式的独热编码列转为长格式,每个节目对应一行其所属的类型,筛选出is_genre=1的行,得到每个节目对应的类型和评分。- 分组统计:按
genre和review score分组,用size()统计每组的节目数量,重命名列名为count,再按类型升序、评分降序排序。 - 去除重复类型名:用
mask和duplicated()把同一类型下的重复名称替换为空字符串,匹配目标格式。
运行代码后得到的结果与目标格式完全一致。
内容的提问来源于stack exchange,提问作者Aloysius
相关产品推荐
相关产品推荐

