How to convert string back to list using Pandas

2019-04-25 12:25发布

I have a txt file with some data and one of the columns is like this:

['BONGO', 'TOZZO', 'FALLO', 'PINCO']

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'] returns a string like this

"['BONGO', 'TOZZO', 'FALLO', 'PINCO']"

instead of a list like this:

['BONGO', 'TOZZO', 'FALLO', 'PINCO']

Therefore if I type df['column'][0] I get '[' instead of BONGO

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?

1条回答
来,给爷笑一个
2楼-- · 2019-04-25 12:28

You can use ast.literal_eval as :

>>> import ast
>>> a = "['BONGO', 'TOZZO', 'FALLO', 'PINCO']"
>>> print ast.literal_eval(a)
>>> ['BONGO', 'TOZZO', 'FALLO', 'PINCO']
查看更多
登录 后发表回答