scott martin
scott martin

Reputation: 1293

Pandas - Splitting rows with multiple values into new row

I have a Dataframe of one column. Some of the rows have multiple value separated by a comma. I would like to have each row have only one value.

Given below is how my Dataframe looks like :

0,apples
1,bananas
2,oranges,kiwis

Expected output:

apples
bananas
oranges
kiwis

Upvotes: 0

Views: 67

Answers (1)

Celso Pereira Neto
Celso Pereira Neto

Reputation: 163

Setting up example:

Import pandas as pd

df = pd.DataFrame({"Apples", "bananas", "oranges, kiwis"})

Using .split()

df = df.apply(lambda r: r[0].split(','), axis=1)

Now you need this in a list, you can use a for loop, but I like list comprehensions:

dlist = [item for row in df for item in row]

Now you can use the list to make a new dataframe:

df_out = pd.DataFrame(dlist)

Upvotes: 1

Related Questions