Skip to content
Advertisement

Copy and split row by if cell condition it met – Pandas Python

I am trying to overcome the issue when I have a cell with specific char(‘;’) which I would like to copy the same line with the amount if splitters that specific cell in specific col got. For example:

Index Name Age Car
1 David 45 Honda;Subaru
2 Oshir 32 BMW

The result that I am trying to get is the following:

Index Name Age Car
1 David 45 Honda
2 David 45 Subaru
3 Oshir 32 BMW

Thanks!

Advertisement

Answer

Possible solution is the following:

import pandas as pd

# set data and create dataframe
data = {"Name": ["David", "Oshir"], "Age": [45, 32], "Car": ["Honda;Subaru", "BMW"]}
df = pd.DataFrame(data)

df = df.assign(Car=df['Car'].str.split(';')).explode('Car').reset_index(drop=True)

df

Returns

enter image description here

Advertisement