Search code examples
pythondataframepython-re

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

Solution

  • 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