Rakesh B
Rakesh B

Reputation: 11

How to extract strings using Regex in pandas based on multiple if-conditions

dframe = pd.DataFrame({'Num':['38-30','38-30','21-51','24-11','34-20'],
'Des':['Generates Vacuum','Pressure low','Ground Problem',
'Leak from Controller','Lock Unserviceable']})

In the above dataframe I want to extract specific strings from Des column based on the Num column. For instance, if Num is equal to 38-30 then extract Vacuum from Des and if it doesn't have Vacuum, then extract Pressure. There are multiple strings that I have to extract for each Num.

I am trying to use re.extract('generator|Pressure',re.I) but I don't know how to include the if statements as I mentioned above.

My output should look like this: enter image description here

Upvotes: 1

Views: 173

Answers (1)

BENY
BENY

Reputation: 323286

Use np.where with findall

np.where(df.Num.eq('38-30'),df.Des.str.findall('generator|vacuum',flags=re.IGNORECASE),'')

Upvotes: 1

Related Questions