You need to enable JavaScript to run this app. 如何使用Pandas将多值列值映射为对应子列的01标识
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Pandas将多值列值映射为对应子列的01标识

Pandas实现多选项列匹配填充0/1标识

处理逻辑

针对存储了逗号分隔多选项值的「Q26 Challenges」列,直接复用已存在的Q26_1~Q26_7全0初始列:当原列内容包含某选项编号时,将对应编号的Q26_x列置1,未命中则保留原有0值。

实现步骤

  1. 导入依赖库,构建初始测试数据集:
import pandas as pd

# 初始数据结构匹配需求描述
df = pd.DataFrame({
    "ID": [1, 2, 3],
    "Q26 Challenges": ["5", "1,2", "1,3,7"],
    "Q26_1": [0, 0, 0],
    "Q26_2": [0, 0, 0],
    "Q26_3": [0, 0, 0],
    "Q26_4": [0, 0, 0],
    "Q26_5": [0, 0, 0],
    "Q26_6": [0, 0, 0],
    "Q26_7": [0, 0, 0]
})
  1. 逐行解析选项值并匹配填充:
  • 对每一行的「Q26 Challenges」值按逗号拆分,过滤掉空字符串
  • 通过选项编号拼接得到对应目标列名(如选项1对应Q26_1),校验列存在后将对应行位置赋值为1
for row_idx, row_data in df.iterrows():
    # 拆分多选项,清理无效空格
    option_list = [opt.strip() for opt in str(row_data["Q26 Challenges"]).split(",") if opt.strip()]
    for opt in option_list:
        target_col = f"Q26_{opt}"
        if target_col in df.columns:
            df.loc[row_idx, target_col] = 1

最终输出效果

处理完成后的数据完全匹配预期要求:

  • ID为1的样本:Q26_5列值为1,其余Q26_x列保持0
  • ID为2的样本:Q26_1、Q26_2列值为1,其余Q26_x列保持0
  • ID为3的样本:Q26_1、Q26_3、Q26_7列值为1,其余Q26_x列保持0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 13:06:03