Extract string if match the value in another list

  • A+
Category:Languages

I want to get the value of the lookup list instead of a boolean. I have tried the following codes:

val = pd.DataFrame(['An apple','a Banana','a cat','a dog']) lookup = ['banana','dog'] # I tried the follow code: val.iloc[:,0].str.lower().str.contains('|'.join(lookup)) # it returns: 0    False 1     True 2    False 3     True Name: 0, dtype: bool 

What I want:

0    False 1    banana 2    False 3    dog 

Any help is appreciated.

 


You can use extract instead of contains, and fillna with False:

import re p = rf'/b({"|".join(lookup)})/b' val[0].str.extract(p, expand=False, flags=re.I).fillna(False)          0 0   False 1  banana 2   False 3     dog 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: