简体   繁体   中英

In Python - How to count the occurrences of the word “price” in each row of the column “content”?

data frame

I hope the data is visible. It is a small textual data frame with row and columns. I need to count the occurrences of a specific word like "price" in each row of a column named "content".

First, let me help you display the dataframe:

date title content
10/10/2010 one thing this price is a low price
10/9/2010 two things price is high
10/8/2010 three things high price is higher price

You can write a python function to get the count of a specific word in the sentence of the content column.

def word_count(sentence, query_word):
    word_list = sentence.split()
    return word_list.count(query_word) 

if __name__=="__main__":
    sentence ='high price is higher price'         
    print(word_count(sentence, 'price'))

Or if you want count all words, try Counter

from typing import Counter

sentence ='high price is higher price'
c = Counter(sentence.split())
print(c['price'])
print(c.most_common())

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM