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

如何将pandas中存储数组的列扩展为多列且无需使用for循环?

无for循环实现方案

场景1:仅标记对应元素是否存在(值为1/0)

直接使用pandas原生向量化方法str.get_dummies即可一行完成,不需要手动遍历:

import pandas as pd

# 示例DataFrame构造
df = pd.DataFrame({
    'gear': [['Hengerfeste', 'LED'], ['LED', 'Bluetooth'], ['Hengerfeste', 'Bluetooth', 'GPS']]
})

# 生成同名字段,存在对应元素标记为1,不存在标记为0
df = pd.concat([df, df['gear'].str.join('|').str.get_dummies()], axis=1)

场景2:需将元素本身的值填入对应列(无匹配填NaN)

如果需要把列表元素的实际值放到对应同名列中,可通过explode加透视的方式实现:

# 按原索引炸开列表列
exploded = df['gear'].explode().reset_index()
# 新增值字段存储列表元素
exploded['val'] = exploded['gear']
# 透视还原为原索引结构,自动生成对应同名列
pivot_res = exploded.pivot(index='index', columns='gear', values='val')
# 结果合并回原DataFrame
df = pd.concat([df, pivot_res], axis=1)
  • 两种方案均为pandas内置向量化操作,无显式for循环,数据量较大时性能远高于手动循环实现
  • 不需要保留原gear列时,后续可通过df.drop('gear', axis=1, inplace=True)删除

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:39:05