I have two dataframes: one dataframe consists of two columns ('good' and bad') and another one that contains text data.
df_dictionary = pd.DataFrame({'good': ['love', 'like'],
'bad': ['dislike', 'hate']})
df_text = pd.DataFrame({'col1': ['i love cats', 'i hate dogs']})
Now I would like to retrieve exact string matches of words that are in the dictionary and are contained in col1 of df_text and assign the string match to the second column of df_text.
I tried .isin(), however this code only shows exact string matches if the whole phrase matches and not if the word is contained in the sentence.
df_text should then look as follows:
| col1 | string_match_good | string_match_bad |
|---|---|---|
| i love cats | love | |
| i hate dogs | hate |
I do not want partial string matches, e.g. if col1 says 'i loved cats', then I do not want a string match.
I found the following:
matches = df_text[df_text['col1'].str.contains(fr"\b(?:{'|'.join(df_dictionary)})\b")] , however this one does not print the matched words (i.e. good or bad) in the string_match columns.
Does anyone have a solution to it?