简体   繁体   English

计算csv文件中的出现次数

[英]Count the occurrences in a csv file

I need to find which year had the most tornadoes occur in LA. 我需要找出在洛杉矶发生龙卷风最多的年份。 I have figured out how to print it, but how would I get it to count and then print the year that had the most tornadoes? 我已经弄清楚了如何打印它,但是如何计算并打印出龙卷风最多的年份呢?

import csv

with open('tornadoes.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:

        if line_count == 0:
            pass

        else:
            if row[idx['st']]=="LA":
                print(row[idx['st']], row[idx['yr']])

        line_count +=1

You can use the collections.Counter.most_common method: 您可以使用collections.Counter.most_common方法:

import csv
from collections import Counter

with open('tornadoes.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    next(csv_reader)
    print(Counter(row[idx['yr']] for row in csv_reader if row[idx['st']] == 'LA').most_common())

What you can do is make a dictionary, and have each year as a key. 您可以做的是制作字典,并将每年作为关键。 Once you checking your file you can just return the max count. 一旦检查完文件,就可以返回最大计数。

import csv
import operator

with open('tornadoes.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')

    line_count, num_tornados = 0, {}

    for row in csv_reader:

        if line_count == 0:
            pass

        else:
            if row[idx['st']]=="LA":
                if row[idx['yr']] in num_tornados:
                    num_tornados[row[idx['yr']]] += 1
                else:
                    num_tornados[row[idx['yr']]] = 1

        line_count +=1
    print(max(num_tornados.iteritems(), key=operator.itemgetter(1))[0])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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