简体   繁体   中英

How to split a string into different columns in python pandas

I have looked at multiple stack overflow questions similar to this, for example, this one and this one . However, my situation is a bit more tedious.

I have column consisting of the following strings

 lineup
0 'FLEX Nick Mullens FLEX Raheem Mostert FLEX Deebo Samuel FLEX Cole Beasley FLEX Jordan Reed CPT Robbie Gould'
1 'FLEX Nick Mullens FLEX Brandon Aiyuk FLEX Cole Beasley FLEX Tyler Bass FLEX Robbie Gould CPT Raheem Mostert'
2 'FLEX Josh Allen FLEX Stefon Diggs FLEX Cole Beasley FLEX Devin Singletary FLEX Richie James CPT Bills'
...

I would like to transform that string into multiple rows, like so:

     FLEX1           FLEX2         FLEX3          FLEX4           FLEX5         CPT
0 Nick Mullens  Raheem Mostert  Deebo Samuel  Cole Beasley     Jordan Reed   Robbie Gould
1 Nick Mullens  Brandon Aiyuk   Cole Beasley  Tyler Bass       Robbie Gould  Raheem Mostert
2 Josh Allen    Stefon Diggs    Cole Beasley  Devin Singletary Richie James  Bills

So, I would like to expand the FLEX and CPT into separate columns, and the following name should be placed in the according column.

I know how to use str.split() , but I'm not sure how to turn part of the string into new columns. Any help is appreciated, thanks!

Use str.slit with expand :

df.lineup.str.split('FLEX|CPT',expand=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM