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

如何使用Pandas的loc方法合并DataFrame分类列中的指定类别?

正确的类别合并实现方法

错误原因分析

你之前的代码逻辑有误:df.genre["History"].value_counts()是用来统计History类别的出现次数,并非筛选目标行的条件,正确的筛选逻辑应该是判断genre列的值是否等于目标类别。

方法一:使用loc逐类修改

这是最直观的方式,针对每个需要合并的类别单独设置:

# 将War合并至Action
df.loc[df['genre'] == 'War', 'genre'] = 'Action'
# 将History合并至Documentary
df.loc[df['genre'] == 'History', 'genre'] = 'Documentary'
# 将Science Fiction合并至Fantasy
df.loc[df['genre'] == 'Science Fiction', 'genre'] = 'Fantasy'

方法二:使用replace批量映射(推荐)

如果需要合并的类别较多,定义一个映射字典一次性完成替换会更高效:

# 定义类别映射规则
genre_merge_map = {
    'War': 'Action',
    'History': 'Documentary',
    'Science Fiction': 'Fantasy'
}

# 执行批量替换
df['genre'] = df['genre'].replace(genre_merge_map)

验证结果

执行完上述代码后,你可以通过以下命令查看合并后的类别统计:

print(df['genre'].value_counts())

此时Action的计数会变为3692+308=4000,Documentary为1334+216=1550,Fantasy为573+502=1075,最终会得到你需要的11个类别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:23:17