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

如何将DataFrame列按//拆分并以字符串值为列名生成0-1标记列

拆分项目领域并生成独热编码DataFrame

原始数据集

import pandas as pd

# 构建原始数据
data = {
    "Name": ["Joe", "Ann", "Ben", "Keren", "Alice"],
    "Dept": ["Biotech", "Biotech", "Math", "Biotech", "Physics"],
    "Project area/areas interested": ["Cell culture//Bioinfo//Immunology", "Cell culture", "Trigonometry//Algebra", "Microbio", "Optics"]
}
df = pd.DataFrame(data)

处理步骤

用pandas的str.get_dummies()方法就能高效完成需求,它会自动按指定分隔符拆分列值,生成对应领域的列,存在该领域标记1,否则标记0:

# 拆分项目领域列,生成独热编码
project_dummies = df["Project area/areas interested"].str.get_dummies(sep="//")

# 合并原始数据与编码列,删除原项目领域列
result_df = pd.concat([df.drop("Project area/areas interested", axis=1), project_dummies], axis=1)

最终结果

执行后得到的DataFrame如下:

NameDeptAlgebraBioinfoCell cultureImmunologyMicrobioOpticsTrigonometry
JoeBiotech0111000
AnnBiotech0010000
BenMath1000001
KerenBiotech0000100
AlicePhysics0000010

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 14:56:30