How to check if nested list is present and unnest if present?

Viewed 86

I have a single row df that looks like this:

id         tags
1         [[[band_music, fun], tv], movies]

Sometimes the df can look like this depending on the source:

id         tags
1         [[[band_music, fun], tv]

or like this:

id         tags
1         [band_music, fun]

or like this:

id         tags
1         fun

How can I check the column if the nested lists are present and unnest them so they are like this:

or like this:

id         tags
1         [band_music, fun,movies,tv]
2 Answers

Using findall

df.tags.astype(str).str.findall("'([^']*)'")
0    [band_music, fun, tv]
Name: tags, dtype: object

Try:

import re
df['tags'][1] = re.split(',', str(df['tags'][1]).replace('[','').replace(']', ''))

Output:

id  tags
1   ['band_music', 'fun', 'tv', 'movies']
Related