How to split a python dataframe into rows based on new line characters?

Viewed 350

With reference to this, I wanted to explode the dataframe into separate columns by splitting the values into newlines as separate rows. The values may contain multiple new lines.

Example Dataframe:

Fruit  |  Store
----------------
Apple  |  Querty
Banana |  Mouz\nVazhai
Grapes |  Angoor\nRangoon

I want this dataframe to be split into the following:

Fruit  |  Store
----------------
Apple  |  Querty
Banana |  Mouz
Banana |  Vazhai
Grapes |  Angoor
Grapes |  Rangoon

Is there any solution to accomplish this?

1 Answers

First split values to lists and then use DataFrame.explode:

df = df.assign(Store = df['Store'].str.split(r'\n')).explode('Store')
Related