I messed up yesterday and saved a datframe to csv and in that dataframe I had a column which was a list of strings. Now that list of strings, is a string(of a list of strings) when I import it back into python from a csv. Is there a way I can, upon importing, change it back to a list of strings?
Example:
testList = localGov["DataElements"][4]
testList
Out[62]: "['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']"
The closest I have been able to come is using the following but it leaves a whitespace in front of some of the characters.
testList.strip("[]").replace("'","").split(",")
Out[74]: ['Ethnicity', ' Sex', ' Cause of Death', ' Count', ' Percent']
That's what ast.literal_eval is for :
>>> from ast import literal_eval
>>>
>>> literal_eval( "['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']")
['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']
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