Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

python - How to split 2 columns with patterns?

I have a dataset (df) with 2 columns of arbitrary length, and I need to split it up based on the value.

BUS CODE
150 H.S.London-lon3 11£150 H.S.London-lon3 16£150 H.S.London-lon3 120 GERI
400 Airport Luton-ptr5 12£400 Airport Luton-ptr5 15£400 Airport Luton-ptr5 17 24£JTR
005 Plaza-cata-md6 08£005 Plaza-cata-md6 012£005 Plaza-cata-md6 18 78£TDE
question from:https://stackoverflow.com/questions/65599404/how-to-split-2-columns-with-patterns

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use .str.extract with regex pattern containing named capturing groups:

code = r'^(?P<code>d+)?.*?(?P<name>[A-Za-z]+)'
bus  = r'^(?P<bus>d+)s(?P<directions>.*?)-(?P<zone>[^-]+)s(?P<time>d+)'

df['BUS'].str.extract(bus).join(df['CODE'].str.extract(code))

   bus     directions  zone time code  name
0  150     H.S.London  lon3   11  NaN  GERI
1  400  Airport Luton  ptr5   12   24   JTR
2  005     Plaza-cata   md6   08   78   TDE

See the regex demo for code pattern here and for bus pattern here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...