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

Time:01-04

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related