Splitting ID column in pandas dataframe to multiple columns

Viewed 188

I have a pandas dataframe like below :

    |  ID      |  Value |
    +----------+--------+
    |1C16      |  34    |
    |1C1       |  45    |
    |7P.75     |  23    |
    |7T1       |  34    |
    |1C10DG    |  34    |
    +----------+--------+

I want to split the ID column (its a string column) in a way that looks like below:

    |  ID      |  Value |  Code | Core |size |
    +----------+--------+-------+------+-----+
    |1C16      |  34    |   C   |  1   | 16  |
    |1C1       |  45    |   C   |  1   |  1  |
    |7P.75     |  23    |   P   |  7   | .75 |
    |7T1       |  34    |   T   |  7   | 1   |
    |1C10DG    |  34    |   C   |  1   | 10  |
    +----------+--------+-------+------+-----+

So how can this be achieved ? Thanks

2 Answers

You can try .str.extract with regex (?P<Code>\d+)(?P<Core>[A-Z])(?P<size>[.0-9]+) to capture the patterns:

df.ID.str.extract(r'(?P<Code>\d+)(?P<Core>[A-Z])(?P<size>[.0-9]+)')

#  Code Core size
#0    1    C   16
#1    1    C    1
#2    7    P  .75
#3    7    T    1
#4    1    C   10

use .str.extract() with multiple capturing groups & join

df.join(
   df['ID'].str.extract('(\d)(\w)(\d+|.\d+)').rename(
           columns={0 : 'Core', 1 : 'Code', 2 : 'Size'}))

       ID  Value Core Code Size
1    1C16   34.0    1    C   16
2     1C1   45.0    1    C    1
3   7P.75   23.0    7    P  .75
4     7T1   34.0    7    T    1
5  1C10DG   34.0    1    C   10
Related