Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 separated into separate columns.

As an example I have data like the following:

Name  Info
Mike  "a, b, c, d"
Joe  "a, f, z"

I need to break these letters out into separate columns. The a's, b's, etc. don't have to line up so that each letter is in the "correct" column. They just need to be broken out into separate columns.

I'm doing this in Python. I'm open to using other libraries like Pandas. There will be other columns included, not just two. I made a simple example.

Any help is appreciated.

like image 582
Eric Shreve Avatar asked Dec 08 '25 17:12

Eric Shreve


2 Answers

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      a      b      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_'))
like image 171
Scott Boston Avatar answered Dec 11 '25 06:12

Scott Boston


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
like image 30
BENY Avatar answered Dec 11 '25 06:12

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!