英文:
How to convert a string list to (object) list in Pandas?
问题
以下是翻译好的代码部分:
我有下面这个字典,其中的值是字符串类型:
data = {'object_1': "['abc']",
'object_2': "['def']",
"object_3": "['xyz']",
"object_4": "['abc']"}
我想将字典的值从字符串类型转换为列表类型。我尝试使用 `literal_eval` 和 `eval()`,但未成功获取纯Python列表:
*期望的输出:*
data = {'object_1': ['abc'],
'object_2': ['def'],
"object_3": ['xyz'],
"object_4": ['abc']}
希望这对你有帮助。
英文:
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 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']}
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论