You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于多变量对独热编码的影视评分数据进行分组排序?

问题描述

我有如下带评分的影视节目数据,已按节目类型完成独热编码(值为0或1):

showreview scoreAction & AdventureAnime FeaturesAnime SeriesBritish TV ShowsChildren & Family Movies
a810000
b1001000
c901000
d600100
e900010
f700001
g800001
h810000

希望按以下规则处理数据:以类型为首要分组依据,评分按降序排列,同时统计对应评分的节目数量,得到如下格式结果:

genrereview scorecount
Action & Adventure82
Anime Features101
91
Anime Series61
British TV Shows91
Children & Family Movies81
71

尝试过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)

代码解释

  1. melt重塑数据:把宽格式的独热编码列转为长格式,每个节目对应一行其所属的类型,筛选出is_genre=1的行,得到每个节目对应的类型和评分。
  2. 分组统计:按genre和review score分组,用size()统计每组的节目数量,重命名列名为count,再按类型升序、评分降序排序。
  3. 去除重复类型名:用mask和duplicated()把同一类型下的重复名称替换为空字符串,匹配目标格式。

运行代码后得到的结果与目标格式完全一致。

内容的提问来源于stack exchange,提问作者Aloysius

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 05:20:24