Find numeric values preceding a substring containing multiple numeri values

  dataframe, pandas, python, python-3.8

I have a dataframe which looks as following:

df['col1'].values

array(['cat 113kd29',     'do56goat24kdasd',     'pig145kd'])

I need to create a new column df['vals'] with following values:

113
24
145

i.e. first I need to look for substring kd and then find the numeric value preceding it. I am not sure how to go about this.

There can be multiple numeric values in each string so I need to find only ones before kd. Please note the string ‘cat 113kd29’. I need to extract only 113 and discard 29. Also look at ‘do56goat24kdasd’

Source: Python Questions

LEAVE A COMMENT