英文:
How to convert a string list to (object) list in Pandas?
问题
Sure, here is the translated code portion:
data = {'object_1': ['abc'],
'object_2': ['def'],
'object_3': ['xyz'],
'object_4': ['abc']}
I hope this helps!
英文:
I have the dictionary below in which the values are string type:
data = {'object_1':"['abc']",
'object_2':"['def']",
"object_3": "['xyz']",
"object_4": "['abc']"}
I want to convert the values of the dictionary from a string type to a list type. I tried to use literal_eval
and eval()
but without any success to get pure python lists:
Desired output:
data = {'object_1':['abc'],
'object_2':['def'],
"object_3": ['xyz'],
"object_4": ['abc']}
Thanks for any advice.
答案1
得分: 0
If I understood correctly, you want to convert the dictionary values from a string "['def']"
to a list containing a string ['def']
, right? If that is the case, you can do it with regex logic.
import re
data = {'object_1':"['abc']",
'object_2':"['def']",
"object_3": "['xyz']",
"object_4": "['abc']"}
exclude_brackets_quotes = lambda args: (args[0], [re.sub("[\[\]']", "", args[1])])
converted_data = dict(map(exclude_brackets_quotes, data.items()))
converted_data
This outputs
{'object_1': ['abc'],
'object_2': ['def'],
'object_3': ['xyz'],
'object_4': ['abc']}
英文:
If I understood correctly, you want to convert the dict values from a string "['def']"
to a list containing a string ['def']
, right? If that is the case you can do it with regex logic.
import re
data = {'object_1':"['abc']",
'object_2':"['def']",
"object_3": "['xyz']",
"object_4": "['abc']"}
exclude_brackets_quotes = lambda args: (args[0], [re.sub("[\[\]']", "", args[1])])
converted_data = dict(map(exclude_brackets_quotes, data.items()))
converted_data
This outputs
{'object_1': ['abc'],
'object_2': ['def'],
'object_3': ['xyz'],
'object_4': ['abc']}
答案2
得分: 0
尝试这样使用 ast.literal_eval
:
import ast
converted_data = {key: ast.literal_eval(value) for key, value in data.items()}
另一个解决方法是使用 strip
,如下所示:
converted_data = {key: [value.strip("[]'")] for key, value in data.items()}
英文:
Try to use ast.literal_eval
this way:
import ast
converted_data = {key: ast.literal_eval(value) for key, value in data.items()}
Another solution is to use strip
like so:
converted_data = {key: [value.strip("[]'")] for key, value in data.items()}
答案3
得分: 0
保存熊猫文件时使用不同的分隔符解决了问题。
英文:
saving the pandas file with different separator saved the day.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论