Skip to content Skip to sidebar Skip to footer

Python Separate Text Into Different Column With Comma

I'm pulling data from a database and writing to a new Excel file for a report. My issue is that the last column of data has data that is separated by commas and needs to be separa

Solution 1:

IIUC:

df.assign(**df['Info'].str.split(',', expand=True).add_prefix('Info_'))

Output:

   Name        Info Info_0 Info_1 Info_2 Info_3
0  Mike  a, b, c, d      ab      c      d
1   Joe     a, f, z      a      f      z   None

Note: You can also use join instead of assign (Using @coldspeed \s* to elimate spaces):

df.join(df['Info'].str.split('\s*,\s*', expand=True).add_prefix('Info_'))

Solution 2:

From pandas str.split

df=pd.concat([df,df.Info.str.split(',',expand=True)],1)
df
Out[611]: 
   Name        Info  0   1   2     3
0  Mike  a, b, c, d  a   b   c     d
1   Joe     a, f, z  a   f   z  None

Post a Comment for "Python Separate Text Into Different Column With Comma"