Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string back to list using Pandas

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?

like image 241
Federico Gentile Avatar asked Feb 20 '17 18:02

Federico Gentile


1 Answers

You can use ast.literal_eval as :

>>> import ast
>>> a = "['BONGO', 'TOZZO', 'FALLO', 'PINCO']"
>>> print ast.literal_eval(a)
>>> ['BONGO', 'TOZZO', 'FALLO', 'PINCO']
like image 100
ZdaR Avatar answered Oct 22 '22 14:10

ZdaR