1

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.

1 Answer 1

2

Use regex:

import re

pattern= '|'.join(['dog','cat','cow','fish'])

df['StrLookUp'] = [re.findall(pattern, i) for i in df['String']]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.