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

如何使用Pandas将DataFrame转换为键为单值、值为列表的字典

实现代码

直接对col_3、col_4列调用pandas自带的字符串拆分方法str.split(),再打包生成字典即可:

import pandas as pd

df = pd.read_csv('data.csv')
# 原col_1映射col_2的字典
dict1 = dict(zip(df['col_1'], df['col_2']))
# col_1映射col_3拆分后列表的字典,若要适配逗号后带空格的场景可把分割符改为r',\s*'
dict3 = dict(zip(df['col_1'], df['col_3'].str.split(',')))
# col_1映射col_4拆分后列表的字典
dict4 = dict(zip(df['col_1'], df['col_4'].str.split(',')))

运行后dict3的输出结果就是你需要的结构:{'John Doe': ['22','35','67']}

可选优化

如果需要把列表里的字符串转为整数方便后续计算,可以加一层lambda对拆分后的列表做类型转换:

dict3 = dict(zip(df['col_1'], df['col_3'].str.split(',').apply(lambda x: [int(i) for i in x])))

如果列中存在空值,可在split方法中添加na_action='ignore'参数避免报错:

dict3 = dict(zip(df['col_1'], df['col_3'].str.split(',', na_action='ignore')))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:15:05