0

I would like to split column hobbies by comma from the following dataframe, then vertically set them respectively:

   id   name       hobbies
0   1   John  TV, computer
1   2  Steve  travel, film
2   3    Jim     swim, jog

How could I get an output like this? Thank you.

   id   name   hobbies
0   1   John        TV
1   1   John  computer
2   2  Steve    travel
3   2  Steve      film
4   3    Jim      swim
5   3    Jim       jog
ah bon
  • 9,293
  • 12
  • 65
  • 148
  • 3
    Use `explode` for version 0.25+ here after splitting the string on comma: `out = df.assign(hobbies=df['hobbies'].str.split(',')).explode('hobbies')` for lower version of pandas , use `m = df.assign(hobbies=df['hobbies'].str.split(','))` and then `out = m.loc[m.index.repeat(m['hobbies'].str.len())].assign(hobbies=np.concatenate(m['hobbies']))` – anky Mar 09 '20 at 10:53
  • 1
    Thank you, I’ll test with my data and let you know. – ah bon Mar 09 '20 at 16:33
  • 1
    It works perfect, you may answer the question with it if you like to. – ah bon Mar 10 '20 at 00:45
  • 1
    That's okay as this has been asked before, I have closed it. – anky Mar 10 '20 at 02:58

0 Answers0