Pandas create multiple columns through multiple regex capture groups

Viewed 917

I have a column in a dataframe that looks like this:

COMPRA DE MANTENIMIENTO INSUMOS OT:15424 PLACA:TSW894 OC:28826

and I want to create two new columns in this way:

df[['OT','OC']] = df['FAC_DESC'].str.extract(r'(OT\S*)(OC\S*)')

But is not working, (both columns fill with NaN's)only works when I use only one capture group or when I use '?' between the capture groups, but only catch the last group. I believe I'm missing something...

1 Answers

The easiest way is to modify your regex pattern to also match the words between OT and OC by adding .*:

df = pd.DataFrame({"col":["COMPRA DE MANTENIMIENTO INSUMOS OT:15424 PLACA:TSW894 OC:28826"]})

df[['OT','OC']] = df['col'].str.extract(r'(OT\S*).*(OC\S*)')

print (df)

                                                 col        OT        OC
0  COMPRA DE MANTENIMIENTO INSUMOS OT:15424 PLACA...  OT:15424  OC:28826
Related