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

如何对DataFrame中多标签topic列实现带前缀的独热编码

解决方案:多标签独热编码(带自定义前缀)

Got it, handling multi-label one-hot encoding with custom prefixes like your requirement is totally straightforward—here are two reliable approaches using pandas and scikit-learn that fit your exact use case:


方法1:纯Pandas实现(直观易理解)

This approach uses pandas built-in string and aggregation functions, great if you want to avoid importing extra libraries:

import pandas as pd

# 1. 将topic列的字符串分割为标签列表(比如"3 12 7"转成["3","12","7"])
df1["topic"] = df1["topic"].str.split()

# 2. 展开每个标签为单独行,生成基础独热编码
one_hot_raw = df1.explode("topic")["topic"].str.get_dummies()

# 3. 按原行索引分组求和,把同一行的多个标签合并成一行的1/0值
one_hot_agg = one_hot_raw.groupby(one_hot_raw.index).sum()

# 4. 给所有编码列添加前缀"S"
one_hot_final = one_hot_agg.add_prefix("S")

# 5. 合并回原text列,得到最终结果
result_df = pd.concat([df1["text"], one_hot_final], axis=1)

逻辑说明:

  • str.split() 把空格分隔的标签字符串拆成列表,方便后续处理
  • explode() 把每个标签拆成单独行,这样get_dummies()能为每个标签生成独立列
  • groupby().sum() 将同一原始行的拆分记录合并,把多个1累加成1(因为同一标签不会重复出现)
  • add_prefix() 直接给列名加上你需要的"S"前缀

方法2:Scikit-learn专业多标签处理

如果你的数据集更大或者需要和其他机器学习流程整合,用MultiLabelBinarizer更高效:

import pandas as pd
from sklearn.preprocessing import MultiLabelBinarizer

# 1. 同样先把topic列转成标签列表
df1["topic"] = df1["topic"].str.split()

# 2. 初始化多标签二值化器
mlb = MultiLabelBinarizer()

# 3. 生成独热编码矩阵
one_hot_matrix = mlb.fit_transform(df1["topic"])

# 4. 转成DataFrame并手动添加前缀"S"
one_hot_df = pd.DataFrame(
    one_hot_matrix,
    columns=[f"S{cls}" for cls in mlb.classes_]
)

# 5. 合并回原text列(注意重置索引避免不匹配)
result_df = pd.concat([df1["text"].reset_index(drop=True), one_hot_df], axis=1)

额外优化:按数字顺序排列编码列

默认情况下,列会按字符串排序(比如S1、S10、S2),如果想按数字顺序排列,可以加这一行:

# 按标签数字大小重新排序列
one_hot_df = one_hot_df.reindex(
    sorted(one_hot_df.columns, key=lambda x: int(x[1:])),
    axis=1
)

注意事项:

  • 如果topic列存在空值或者无效字符,先做清洗:比如df1["topic"] = df1["topic"].fillna("").str.split()
  • 两种方法最终生成的结果完全一致,选哪种取决于你的代码环境和习惯

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 07:17:42