Python to list vs explode

Viewed 50
Set.Categories.str.split(',').tolist()


Set.Categories.str.split(',')).explode('Categories')

what is the difference between tolist and explode in pandas?

1 Answers

Those are completely different functions.

The first one returns (here, nested) python lists:

df = pd.DataFrame({'Categories': ['a,b','c,d','e']})

df['Categories'].str.split(',').tolist()
[['a', 'b'], ['c', 'd'], ['e']]

The second one expands the rows of the Series to have one row per initial list item:

df = pd.DataFrame({'Categories': ['a,b','c,d','e']})

df['Categories'].str.split(',').explode('Categories')

0    a
1    b
2    c
3    d
4    e
Name: Categories, dtype: object
Related