简体   繁体   中英

Split the single alphanumeric string column to two columns as numbers and alphabets

I have a single alphanumeric string column that has to be split into two different columns: numbers and alphabet. But the thing is we just need to split the first part of numbers from string and the remaining alphanumeric should remain same in 2nd column

For example:

Col A
2 Nutsx20mm
2 200 jibs50
3 200
5
8 Certs 20

Expected:

A1 A2
2 Nutsx20mm
2 200 jibs50
3 200 null
5 null
8 Certs 20

I have tried out, It works correctly but fails when the string is just a 4 digit number with space.

code:
df_tab["Col A"].str.extract(r'(\d+)(?: (\S.+))?$')

The output I get is below table:

A1 A2
2 Nutsx20mm
2 200 jibs50
3 200
5
8 Certs 20

Small change in the regex works

Code:

df["Col A"].str.extract(r'([\d\s]+)(?: (\S.+))?$')

Change:

Previous your regex was matching only digits. Changed it to match digits and numbers.

Output:

2   Nutsx20mm
2 200   jibs50
3 200   NaN
5   NaN
8   Certs 20
df_tab["Col A"].str.extract(r'(\d+(?:\s\d+)*)(?: (\S.+))?$')

This will capture any additional number only blocks of text.

Tested with:

2 300
2 300 400
2 nuttx20mm
2 300 mutt

regex101.com is useful for writing and testing regex and is what I used for this answer.

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