Convert a columns of string to list in pandas
Use str.strip
and str.split
:
df['LABELS'] = df['LABELS'].str.strip('()').str.split(',')
But if no NaN
s here, list comprehension
working nice too:
df['LABELS'] = [x.strip('()').split(',') for x in df['LABELS']]
You can use ast.literal_eval
, which will give you a tuple:
import ast
df.LABELS = df.LABELS.apply(ast.literal_eval)
If you do want a list, use:
df.LABELS.apply(lambda s: list(ast.literal_eval(s)))
Sorry I was late to the party. So for other latecomers I got this to work based on the above replies:
df['hashtags'] = df.apply(lambda row: row['hashtags'].strip('[]').replace('"', '').replace(' ', '').split(',') , axis=1)
I loaded a csv with some columns looking like this ...,['hashtag1','hashtag2'],... and the Panda DataFrame loaded it as a string object. I used the above code and it converted to list. I then used "explode" to flatten the data.