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

pandas如何快速将列中100+字符串标签批量替换为对应数值

Pandas 多分类标签批量自动编码实现方法

如果不需要自定义标签与编码的对应关系,仅需要为每个唯一分类标签分配唯一整数编码,可直接用pandas内置能力实现,无需手动编写映射规则:

方法1:最简快速实现

直接将目标列转为分类类型,调用内置codes属性即可自动生成编码,100+标签也可秒级处理:

# 假设需要处理的分类列名为category_col,生成的编码列名为category_encoded
df['category_encoded'] = df['category_col'].astype('category').cat.codes
  • 特性:自动为所有唯一分类标签分配从0开始的连续整数,缺失值会自动编码为-1;如果需要编码从1开始,直接在末尾加1即可:df['category_encoded'] = df['category_col'].astype('category').cat.codes + 1

方法2:可复用映射规则实现

如果后续需要在其他数据集(如测试集)上使用相同的编码规则,可以先手动生成映射字典保存,再应用编码:

# 生成分类标签到编码的映射字典
label_map = {label: idx for idx, label in enumerate(df['category_col'].unique())}
# 应用映射完成编码
df['category_encoded'] = df['category_col'].map(label_map)
  • 扩展需求:如果需要按分类出现频率排序分配编码(出现频率越高编码值越小),可使用如下逻辑生成映射字典:
# 按分类出现频率降序排序
sorted_labels = df['category_col'].value_counts().index.tolist()
label_map = {label: idx for idx, label in enumerate(sorted_labels)}
df['category_encoded'] = df['category_col'].map(label_map)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:36:04