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

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

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.

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

发表评论

匿名网友

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

确定