微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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模块并将文件读入字典,然后根据邮政编码中的唯一值对字典进行排序,但似乎没有任何进展。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。