如何用Pandas将DataFrame中字符串列表转为真实列表并生成目标JSON?
解决Pandas读取Excel后将列表字符串转为实际列表并生成目标JSON的问题
问题背景
你的Excel文件结构如下:
| Title | List |
|---|---|
| Title_1 | ['str_1', 'str_2'] |
| Title_2 | ['str_3', 'str_4'] |
你希望将其转换为如下JSON结构:
{"0":{"Title": "Title_1", "List": ['str_1', 'str_2']}, "1":{"Title": "Title_2", "List": ['str_3', 'str_4']}}
而非带字符串列表的结构:
{"0":{"Title": "Title_1", "List": "['str_1', 'str_2']"}, "1":{"Title": "Title_2", "List": "['str_3', 'str_4']"}}
你尝试了以下代码,得到的是后者的结果:
df = pd.read_excel("my_excel.xlsx") df.to_dict("index")
解决方案
问题核心在于Excel中的List列是字符串格式的列表,Pandas读取时会将其识别为普通字符串,需要先将该列转换为实际的Python列表,再生成目标字典。
方法1:使用ast.literal_eval(推荐,安全可靠)
ast.literal_eval可以安全解析字符串形式的Python字面量(如列表、字典),不会执行恶意代码:
import pandas as pd import ast # 读取Excel文件 df = pd.read_excel("my_excel.xlsx") # 将List列的字符串转为实际列表 df['List'] = df['List'].apply(ast.literal_eval) # 转换为目标格式的字典 result = df.to_dict("index")
方法2:使用eval(不推荐,存在安全风险)
如果能确保Excel内容绝对安全,也可以用eval,但该方法会执行任意字符串代码,不可用于不可信数据:
import pandas as pd df = pd.read_excel("my_excel.xlsx") df['List'] = df['List'].apply(eval) result = df.to_dict("index")
方法3:手动分割字符串(适合格式固定的场景)
如果列表格式完全固定(首尾为方括号、元素用单引号和逗号分隔),可以手动处理字符串:
import pandas as pd def str_to_list(s): # 去除首尾方括号,分割元素后去除单引号 return [item.strip("'") for item in s.strip('[]').split(', ')] df = pd.read_excel("my_excel.xlsx") df['List'] = df['List'].apply(str_to_list) result = df.to_dict("index")
处理后调用to_dict("index"),就能得到你需要的结构,其中List字段为实际的列表类型而非字符串。
内容的提问来源于stack exchange,提问作者JetWing
相关产品推荐
相关产品推荐

