【问题标题】:How to find a particular word in a csv file in a particular column with pandas如何使用熊猫在特定列中的csv文件中查找特定单词
【发布时间】:2022-01-08 09:10:25
【问题描述】:

我想在 csv 文件中搜索特定单词并计算有多少单词,我正在使用 pandas 使用 usecols 获取特定列并使用 str.find 搜索该单词,但它只是返回整列

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

【问题讨论】:

    标签: python pandas list dataframe csv


    【解决方案1】:

    我实际上会导入 csv 并使用 DictReader。代码如下所示:

    import csv
    
    with open('csv-file.csv', newline='') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        
        word_count = 0
        for line in csv_reader:
            if line['author'] == searchitem:
                word_count += 1
    

    【讨论】:

      【解决方案2】:

      试试这个:

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

      编辑:

      据我了解,您对两个非常不同的事物使用相同的变量名。它有效,但最佳做法不推荐使用。

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

      【讨论】:

      • 谢谢你,这才有效
      猜你喜欢
      • 2019-02-12
      • 2013-08-05
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多