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

如何基于Pandas DataFrame列表列批量标记对应列为1?

解决方案

方法一:用explode+crosstab高效实现

这种方法适合B列包含的数字较多、目标列需要自动匹配的场景,无需手动指定列名:

import pandas as pd

asd = pd.DataFrame({"A": ['a', 'b', 'c', 'd'],
                   "B": [[1,2], [1], [1,3], [1]],
                   '1': [0,0,0,0],
                   '2':[0,0,0,0],
                   '3':[0,0,0,0]})

# 展开B列的列表,生成索引与数字的交叉表
exploded_df = asd.explode('B')
binary_table = pd.crosstab(exploded_df.index, exploded_df.B).astype(int)

# 把交叉表的列名转为字符串,匹配原DataFrame的列名格式
binary_table.columns = binary_table.columns.astype(str)

# 用生成的二进制表覆盖原DataFrame的对应列
asd[binary_table.columns] = binary_table

print(asd)

方法二:遍历目标列手动赋值

如果已知需要处理的列(如'1'、'2'、'3'),可以直接遍历这些列,逐行检查B列是否包含对应数字:

import pandas as pd

asd = pd.DataFrame({"A": ['a', 'b', 'c', 'd'],
                   "B": [[1,2], [1], [1,3], [1]],
                   '1': [0,0,0,0],
                   '2':[0,0,0,0],
                   '3':[0,0,0,0]})

# 遍历每个目标列,将列名转为整数后检查是否在B的列表中
for col_name in ['1', '2', '3']:
    target_num = int(col_name)
    asd[col_name] = asd['B'].apply(lambda row: 1 if target_num in row else 0)

print(asd)

常见问题排查

如果你的for循环没成功,通常是这两个原因:

  • 没有将列名(字符串格式)转换成整数,去匹配B列里的数字元素
  • 错误地遍历每行再逐个修改列值,这种方式不仅效率低,还容易因索引问题导致赋值错误

内容的提问来源于stack exchange,提问作者Albert Fredy Rudolph Oppliger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:27:25