I'm trying to explode a string in python pandas by a delimiter but it isn't working

23 Views Asked by At
df = pd.DataFrame({'index': 1 , 2],
                  'artist': ['Elton John', 'Biffy Clyro'],
                  'song': ['Rocket Man', 'Bubbles']
                  'id': ['B12, U6, Z5', 'H91, D293, P292']})

I need to explode these so that it looks like this:

index artist song id
1 Elton John Rocket Man B12
1 Elton John Rocket Man U6
1 Elton John Rocket Man Z5
2 Biffy Clyro Bubbles H91
2 Biffy Clyro Bubbles D293
2 Biffy Clyro Bubbles P292

I ran this code in line with this question I found:

df['id'] = df['id'].str.split(", ")
df.explode('id')

But alas! It returned the same as before but with the spaces in the id column removed, so it looked like this:

index artist song id
1 Elton John Rocket Man B12,U6,Z5
2 Biffy Clyro Bubbles H91,D293,P292

If I tack the second line of code onto the first as I saw suggested in another thread it just gives me one id.

```
df['id'] = df['id'].str.split(", ").explode('id')
```
index artist song id
1 Elton John Rocket Man B12
2 Biffy Clyro Bubbles H91

What am I doing wrong?

0

There are 0 best solutions below