如何在Pandas中将字符串列表转换为(对象)列表?

huangapple go评论59阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月21日 01:47:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75793632-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定