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:
JavaScript
x
10
10
1
import pandas as pd
2
3
# set data and create dataframe
4
data = {"Name": ["David", "Oshir"], "Age": [45, 32], "Car": ["Honda;Subaru", "BMW"]}
5
df = pd.DataFrame(data)
6
7
df = df.assign(Car=df['Car'].str.split(';')).explode('Car').reset_index(drop=True)
8
9
df
10
Returns