Home > Software engineering >  Split and join a column in dataframe
Split and join a column in dataframe

Time:03-24

I have a column dataframe which has the following structure:

Initial-column
--------------
abc:123-456
dsf:231-436
ghi:173-486
jkl:193-156
mnq:120-256

I want to obtain the following columns:

Index    Name   Coords
----     ----   ----     
 0        abc    123
 1        abc    456
 2        dsf    231
 3        dsf    436
 4        ghi    173
 5        ghi    486
 6        jkl    193
 7        jkl    156
 8        mnq    120
 9        mnq    256

I am able to obtain Name and Coords but in two different columns, but I do not know how to combine them. Any ideas?

df[['Name', 'CoordN']] = df['Initial-column'].str.split(':', expand=True)
df[['Coords0', 'Coords1']] = df['CoordN'].str.split('-', expand=True)

CodePudding user response:

You can leverage pd.concat for that:

df = pd.DataFrame(pd.concat([df.Coords0,df.Coords1])).sort_index()
  • Related