Home > Software engineering >  How to find a particular word in a csv file in a particular column with pandas
How to find a particular word in a csv file in a particular column with pandas

Time:12-02

I want to search for a particular word in a csv file and count how many words are there , I'm using pandas to get the particular column using usecols and using str.find to search the word , but it is just returning the whole column

def read(searchitem): 
  lst = ["author"] 
  df=pd.read_csv('data.csv',usecols=lst)
  df = df["author"].str.find(searchitem)
  print(df)
  
read('IMoRT')

CodePudding user response:

Try this:

df["author"].str.count(searchitem).sum()

EDIT:

As I understand it, you are using the same variable name for two very different things. It works, but is not recommended by best practices.

def read(searchitem): 
  lst = ["author"] 
  df=pd.read_csv('data.csv',usecols=lst)
  countWord = df["author"].str.count(searchitem).sum()
  print(countWord)

CodePudding user response:

I would actually import csv and use DictReader. The code would look like this:

import csv

with open("csv-file.csv", "r") as csv_file:
    csv_reader = csv.DictReader(csv_file)
    
    word_count = 0
    for line in csv_reader:
        if line["author"] == searchitem:
            word_count  = 1
  • Related