I know the following function will simply return a count of a word in a sentence. I'm trying to loop through a df['col'] using a list of words. I currently have my function set up to loop over each row. But I'd like to know if there's a way to avoid using a nested loop.
def count_occurrences(word, sentence):
return sentence.lower().split().count(word)
For example, say my column is as below. I want to count how many times the words in the following list occurs in each sentence e.g.
list_of_words = ['green','apple']
ind | df['col']
------------------------------------------
1. | 'green apple red apple blue apple'
2. | 'green apple green apple green apple'
Output:
[4,6]