I have a series of substrings that I want to check against a DataFrame column. For example:
SubStr = pd.series(['dog','cat','cow','fish'])
The DataFrame has a column called "String" where:
df['String'] = (['The dog went for a Walk.','The fish was in the lake.','The dog was barking'])
I want to add a column to the DataFrame that contains the SubStr found in 'String' for that row or just NaN if none of them are found. In my example the new column should contain:
df['StrLookUp'] = ['dog','fish','dog']
In my search research I was able to find examples of where elements of a series are searched for any items in a list, but none of them returned the specific element that was found.
Use regex:
import re
pattern= '|'.join(['dog','cat','cow','fish'])
df['StrLookUp'] = [re.findall(pattern, i) for i in df['String']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.