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

Pandas处理CSV时如何用字符串字面量替代表头列名生成嵌套字典

解决方案

方法1:无需额外新增列(推荐)

直接在apply逻辑中构造指定结构的字典,不需要依赖CSV中不存在的type列,性能更高:

import pandas as pd
import json
import os

csv = "/Users/me/file.csv"
csv_file = pd.read_csv(csv, sep=",", header=0, index_col=False)
csv_file['org'] = csv_file['location'].apply(lambda x: {"location": x, "type": "foo"})

方法2:先新增固定值的type列

如果你后续其他业务逻辑也需要用到统一值的type列,可以先给DataFrame新增该列,再沿用你原来的生成org列的逻辑:

import pandas as pd
import json
import os

csv = "/Users/me/file.csv"
csv_file = pd.read_csv(csv, sep=",", header=0, index_col=False)
# 给所有行的type列赋值为固定字符串foo
csv_file['type'] = 'foo'
csv_file['org'] = csv_file[['location', 'type']].apply(lambda s: s.to_dict(), axis=1)

两种方法最终生成的org列结构完全一致,你可以根据自己的后续使用场景选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:33:02