字符串格式的熊猫列表到字典列表

时间:2021-05-25 10:18:09

标签: python-3.x pandas dataframe

我有一个数据框,其中有一个名为 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}
]

1 个答案:

答案 0 :(得分:1)

对于我在此示例数据中使用 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}]