首页 > 解决方案 > 字符串格式的 Pandas 列表到 dict 列表

问题描述

我有一个数据框,其中有一列名为 coor,它在列表中具有 dict 作为字符串。

df['coor'][0]

'[{'x': 720.65215, 'y': 636.51048, 'width': 332.19348, 'height': 648.12561}, {'x': 2044.77989, 'y': 847.90622, 'width': 329.87049, 'height': 576.11169}]'

我尝试了一些项目,如 json 加载、字符串到列表的转换。没有结果。输出

[
{'x': 720.65215, 'y': 636.51048, 'width': 332.19348, 'height': 648.12561},
{'x': 2044.77989, 'y': 847.90622, 'width': 329.87049, 'height': 576.11169}
]

标签: python-3.xpandasdataframe

解决方案


对于我ast.literal_eval在这个示例数据中工作:

import ast

#changed not valid `''` to `""` around string
a = "[{'x': 720.65215, 'y': 636.51048, 'width': 332.19348, 'height': 648.12561}, {'x': 2044.77989, 'y': 847.90622, 'width': 329.87049, 'height': 576.11169}]"

print (ast.literal_eval(a))
[{'x': 720.65215, 'y': 636.51048, 'width': 332.19348, 'height': 648.12561},
 {'x': 2044.77989, 'y': 847.90622, 'width': 329.87049, 'height': 576.11169}]

推荐阅读