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?
You can use ast.literal_eval
as :
>>> import ast
>>> a = "['BONGO', 'TOZZO', 'FALLO', 'PINCO']"
>>> print ast.literal_eval(a)
>>> ['BONGO', 'TOZZO', 'FALLO', 'PINCO']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With