如何使用 pandas 将字符串转换回列表 [英] How to convert string back to list using Pandas
问题描述
我有一个包含一些数据的txt文件,其中一列是这样的:
I have a txt file with some data and one of the columns is like this:
['BONGO', 'TOZZO', 'FALLO', 'PINCO']
为了加载文件,我使用了熊猫函数to_csv
.
In order to load the file I use the pandas function to_csv
.
一旦加载了数据框,看起来内容就可以了,但是随后我意识到,数据框内的项目不是项目列表,而是一个字符串,其元素是列表中的字符!
Once the dataframe is loaded it looks like the content is ok but then I realize that the item within the dataframe is not a list of items but a string whose elements are the characters of the list!
df['column']
返回这样的字符串
"['BONGO', 'TOZZO', 'FALLO', 'PINCO']"
而不是像这样的列表:
['BONGO', 'TOZZO', 'FALLO', 'PINCO']
因此,如果我键入df['column'][0]
,则会得到'['
而不是BONGO
Therefore if I type df['column'][0]
I get '['
instead of BONGO
我应该怎么做才能将字符串转换回其原始列表格式?我应该使用to_csv
函数的任何输入吗?
What should I do in order to transform the string back to its original list format? Is there any input to the to_csv
function that I should use?
推荐答案
您可以将ast.literal_eval
用作:
>>> import ast
>>> a = "['BONGO', 'TOZZO', 'FALLO', 'PINCO']"
>>> print ast.literal_eval(a)
>>> ['BONGO', 'TOZZO', 'FALLO', 'PINCO']
这篇关于如何使用 pandas 将字符串转换回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!