zizamuft
zizamuft

Reputation: 93

how to split and get the first 2 element in python?

I have this kind of dataframe

df.Product_ID
0       FDP37
1       FDI04
2       FDV02
3       FDT55
4       FDG21
        ...  
4135    FDD08
4136    DRA59
4137    FDK46
4138    FDD09
4139    FDO22

how do i split the first 2 elements into 2 column

let say I want the output comes like this

0       FD    P37
1       FD    I04
2       FD    V02
3       FD    T55
4       FD    G21

I've tried to read and understand txt.split() https://www.w3schools.com/python/ref_string_split.asp but, it shows some kind of separator like " " or ", " compares to what I have above that have no separator

Upvotes: 0

Views: 2750

Answers (2)

Henry Yik
Henry Yik

Reputation: 22493

Slicing might be faster, but here is a regex alternative:

print (df["Product_ID"].str.extract("(?P<Product_ID_FD>.{2})(?P<Product_ID_LD>.*)"))

     Product_ID_FD Product_ID_LD
0               FD           P37
1               FD           I04
2               FD           V02
3               FD           T55
4               FD           G21
4135            FD           D08
4136            DR           A59
4137            FD           K46
4138            FD           D09
4139            FD           O22

Upvotes: 1

eroot163pi
eroot163pi

Reputation: 1815

You can refer to .str of pandas text column. df.assign is same as assigning two times for two columns. It is syntactic sugar

import pandas as pd

df = pd.DataFrame({'Product_ID': {0: 'FDP37', 1: 'FDP37', 2: 'FDP37', 3: 'FDP37', 4: 'FDP37'}})

df = df.assign(first_two=df.Product_ID.str[:2], from_two=df.Product_ID.str[2:])

# Also pass as dictionary with unwrapping for more general
# kwargs = {'first_two': df.Product_ID.str[:2], 'from_two': df.Product_ID.str[2:]}
# df.assign(**kwargs)

print(df)

Upvotes: 1

Related Questions