Python CSV-需要基于一个键对值进行分组和计算

问题描述

我已经记录了一些步骤以帮助澄清问题:

import csv
from collections import defaultdict

# a dictionary whose value defaults to a list.
data = defaultdict(list)
# open the csv file and iterate over its rows. the enumerate()
# function gives us an incrementing row number
for i, row in enumerate(csv.reader(open('data.csv', 'rb'))):
    # skip the header line and any empty rows
    # we take advantage of the first row being indexed at 0
    # i=0 which evaluates as false, as does an empty row
    if not i or not row:
        continue
    # unpack the columns into local variables
    _, zipcode, level = row
    # for each zipcode, add the level the list
    data[zipcode].append(float(level))

# loop over each zipcode and its list of levels and calculate the average
for zipcode, levels in data.iteritems():
    print zipcode, sum(levels) / float(len(levels))

输出

19102 21.4
19003 29.415
19083 29.65

解决方法

我有一个简单的3列csv文件,我需要使用python根据一个键对每一行进行分组,然后对另一个键的值求平均值并返回它们。文件是标准的csv格式,因此已设置;

ID,ZIPCODE,RATE
1,19003,27.50
2,31.33
3,19083,41.4
4,17.9
5,19102,21.40

因此,基本上我需要做的是计算该文件中每个唯一邮政编码col [1]的平均费率col [2]并返回结果。因此,获得19003、19083等所有记录的平均费率。

我研究过使用csv模块并将文件读入字典,然后根据邮政编码中的唯一值对字典进行排序,但似乎没有任何进展。

任何帮助/建议表示赞赏。