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

如何对含多标签的列执行One Hot Encoding?解决Pandas get_dummies局限

解决多标签列的One-Hot编码问题

这是处理多标签数据时很常见的场景——直接用pd.get_dummies()会把整个逗号分隔的字符串当作单一类别,自然没法拆分出独立的标签列。不过pandas提供了两种简单的方法来解决这个问题,我给你详细演示:

方案1:使用str.get_dummies()(最简洁)

这个方法是专门为逗号分隔的字符串列设计的,能直接拆分标签并生成One-Hot编码:

import pandas as pd

# 加载你的数据集
df = pd.DataFrame({
    'id': [1, 2],
    'question': ['What is your name', 'What is your name'],
    'category': ['Introduction', 'Introduction'],
    'tags': ['Introduction', 'Introduction, work'],
    'day': [1, 1],
    'quarter': [3, 3],
    'group_id': [0, 1]
})

# 拆分tags列并生成One-Hot编码,注意分隔符要匹配你的数据(这里是", ")
tags_onehot = df['tags'].str.get_dummies(sep=', ')

# 将编码结果和原数据合并(去掉原tags列)
final_df = pd.concat([df.drop('tags', axis=1), tags_onehot], axis=1)

print(final_df)

运行后你会得到这样的结果:

id             question      category  day  quarter  group_id  Introduction  work
0   1  What is your name  Introduction    1        3         0             1     0
1   2  What is your name  Introduction    1        3         1             1     1

方案2:使用explode() + pd.get_dummies()(更灵活)

如果你的场景需要对标签做更多预处理(比如去重、清理),可以先把标签拆成列表,再展开成多行,最后编码聚合:

import pandas as pd

df = pd.DataFrame({
    'id': [1, 2],
    'question': ['What is your name', 'What is your name'],
    'category': ['Introduction', 'Introduction'],
    'tags': ['Introduction', 'Introduction, work'],
    'day': [1, 1],
    'quarter': [3, 3],
    'group_id': [0, 1]
})

# 把tags字符串拆成列表
df['tags'] = df['tags'].str.split(', ')

# 将列表展开成多行(每个标签对应一行)
exploded_df = df.explode('tags')

# 对展开后的tags列做One-Hot编码
tags_onehot = pd.get_dummies(exploded_df['tags'])

# 合并后按id聚合(用max确保每个标签在原行中存在就标记为1)
final_df = exploded_df.drop('tags', axis=1).join(tags_onehot).groupby('id').max()

print(final_df)

这个方法得到的结果和方案1完全一致,但能应对更复杂的标签处理需求(比如标签有空格、需要先清洗等)。

关键说明

  • 一定要注意分隔符的匹配:如果你的标签是用","而不是", "分隔的,记得把sep参数改成',',否则会出现带空格的标签名(比如' work')。
  • str.get_dummies()是最直接的解决方案,适合大多数简单场景;explode的方法更灵活,适合需要中间步骤处理标签的情况。

内容的提问来源于stack exchange,提问作者Naveen Honest Raj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:40:37