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

如何在Pandas DataFrame中将非Top3行业类别统一映射为类别3?

解决Pandas DataFrame类别映射问题

你之前的问题出在对map方法的na_action参数理解有误:这个参数仅用于处理原列中的NaN值,无法将未匹配到映射字典的其他类别转为3,所以那些不在字典里的类别会被映射为NaN。

下面是两种可行的解决方法:

方法一:map + fillna

先通过字典映射指定类别,再将未匹配生成的NaN统一填充为3:

# 定义指定类别的映射关系
category_mapping = {
    'Manufacturing': 0,
    'Financial Services': 1,
    'Health': 2
}

# 执行映射并填充未匹配项
combined_copy['job_industry_category'] = (
    combined_copy['job_industry_category']
    .map(category_mapping)
    .fillna(3)
    .astype(int)  # 转为整数类型,可选
)

方法二:np.where 条件判断

通过条件判断直接区分目标类别和其他类别,逻辑更直观:

import numpy as np

# 定义目标类别及对应值
target_categories = ['Manufacturing', 'Financial Services', 'Health']
target_values = [0, 1, 2]
category_map = dict(zip(target_categories, target_values))

# 条件映射:属于目标类别则按字典映射,否则设为3
combined_copy['job_industry_category'] = np.where(
    combined_copy['job_industry_category'].isin(target_categories),
    combined_copy['job_industry_category'].map(category_map),
    3
).astype(int)

两种方法都能实现需求,你可以根据习惯选择。如果原列中有NaN值,两种方法都会把NaN转为3;如果想保留原NaN,可以在fillna时加入条件,或者调整np.where的判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:16:10