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

如何按行将pandas列转换为列表并基于name列生成对应字典

问题解法

测试用DataFrame构造(已有数据可跳过)

import pandas as pd
data = [
    [85643, '234,34,11223,345,345_2', 'aasd1', 'vaasd1', '2234,354,223,35,3435', 'G-0001', 1, None, 3, 1],
    [85644, '2343,355,121,34', 'aasd2', '', '', 'G-0001', 2, 56.0, 4, 22],
    [8564312, '24 , 23 ,244 ,2421 ,567 ,789', 'aabsd1', '', '', 'G-0002', 3, None, 32, 33],
    [8564314, '87 ,35 ,67_1', 'aabsd2', 'averabsd', '387 ,355 ,667_1', 'G-00002', 4, 89.0, 43, 44]
]
columns = ['id1', 'ids1', 'Name1', 'Name2', 'ids2', 'ID', 'col1', 'Goal', 'col2', 'col3']
df = pd.DataFrame(data, columns=columns)

核心实现代码

# 统一处理ids列的空格、分割逻辑
def process_ids(ids_str):
    return ids_str.replace(' ', '').split(',')

result_dict = {}

# 处理Name1、ids1、id1组
for _, row in df.iterrows():
    name = str(row['Name1']).strip()
    if not name or name == 'nan':
        continue
    id_val = str(row['id1'])
    ids_list = process_ids(str(row['ids1']))
    final_list = [id_val] + ids_list
    result_dict[name] = final_list
    # 打印要求的变量赋值格式
    print(f"{name} = {final_list}")

# 处理Name2、ids2、id1组
for _, row in df.iterrows():
    name = str(row['Name2']).strip()
    ids_str = str(row['ids2']).strip()
    if not name or name == 'nan' or not ids_str or ids_str == 'nan':
        continue
    id_val = str(row['id1'])
    ids_list = process_ids(ids_str)
    final_list = [id_val] + ids_list
    result_dict[name] = final_list
    # 打印要求的变量赋值格式
    print(f"{name} = {final_list}")

# 输出最终字典
print("dic =", result_dict)

输出验证

运行代码后会直接输出你要求的列表赋值格式,result_dict就是最终需要的字典,完全匹配你的需求:

  • 自动移除ids列的多余空格
  • 自动跳过空值的Name/ids列,不会生成无效条目
  • 所有元素统一为字符串格式,和预期输出一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:15:04