在Python中读取CSV文件并创建字典

3 投票
3 回答
8485 浏览
提问于 2025-04-17 19:01

我有一个这样的csv数据集:

A, 10, USA
B,30, UK
C,4,IT
A,20,UK
B,10,USA

我想读取这些csv行,并提供以下输出:

A has ran 30 miles with average of 15. 
B has ran 30 miles with average of 20.
C has ran 4 miles with average of 4. 

到目前为止,我的解决方案是读取csv数据,把它们转换成字典,然后遍历这些字典,看看'A'出现了多少次,以及它的值是什么,以便计算平均值,最后得出结果。我已经写了这段代码,但我在高效计算'A'出现的次数和累加里程数方面遇到了困难,以便生成我的最终输出。你有什么建议可以在Python中做到这一点吗?对我来说,在C#中做这件事相对简单,但我在Python方面还不太熟练。

def main(filename):
    f = open(filename,'r')
    labels = ['name','miles','country']
    data = csv.DictReader(f,labels,delimiter=',')
    for line in data:
        print (line['name']+"  " + "has ran" +"   "+  line['miles']+" "+"miles")

    f.close()

3 个回答

1

你可以按照以下步骤操作:

  1. 给你的数据加一个表头(比如,“跑步者, 距离, 国家”)。
  2. 把它保存到一个文件里(比如,log.csv)。
  3. 用这里的load_csv函数加载这个文件:https://github.com/kdavies4/ModelicaRes/blob/master/modelicares/util.py#L676,你需要先下载util.py文件,然后按照下面的步骤操作:

    from util import load_csv
    d = load_csv("log.csv")
    

    这样你就会得到一个字典,内容如下:

    d = {'Runner': ['A', 'B', 'C', 'A', 'B'], 'Distance': [10, 30, 4, 20, 10], 'Country': ['USA', 'UK', 'IT', 'UK', 'USA']}
    

    load_csv函数会使用csv.reader自动创建一个字典,字典的键是表头里的内容。每个键对应的字典项是一个列表,里面存的是对应列的值。你可以在这里查看文档: http://kdavies4.github.io/ModelicaRes/util.html#modelicares.util.load_csv。util.py文件里还有很多其他的函数,但你可以安全地把它们删掉(只要保留最上面的import numpy as np)。

  4. 运行下面的代码来计算平均距离:

    # Create counter dictionaries for the statistics.
    from collections import Counter
    n_runs = Counter()
    totals = Counter()
    
    # Calculate the total distance.
    for runner, distance in zip(d['Runner'], d['Distance']):
        n_runs[runner] += 1
        totals[runner] += distance
    
    # Print the results.
    for runner in set(d['Runner']):
        print("%s has run %i miles with an average of %g."
              % (runner, totals[runner], totals[runner]/float(n_runs[runner])))
    

这样你应该能得到想要的结果,而且如果数据增加(无论是行还是列),这个方法也能灵活应对。

Kevin

1

在你的循环中,可以这样使用split:

var1, var2, var3 = line.split(",")

这样做会把这一行中的每个值都放到不同的变量里。然后你就可以随意使用这些变量了。

6

你可以使用一个叫做 defaultdict 的东西来存储值,然后把它们打印出来:

import csv

from collections import defaultdict

with open(filename, 'r') as handle:
    reader = csv.DictReader(handle, ['name', 'miles', 'country'])
    data = defaultdict(list)

    for line in reader:
        data[line['name']).append(int(line['miles']))

    for runner, distances in data.items():
        print '{} ran a total of {} miles and an average of {} miles'.format(
            runner, sum(distances), sum(distances) / float(len(distances))
        )

撰写回答