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

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

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

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

import csvfrom 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 numberfor 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    _, zippre, level = row    # for each zippre, add the level the list    data[zippre].append(float(level))# loop over each zippre and its list of levels and calculate the averagefor zippre, levels in data.iteritems():    print zippre, sum(levels) / float(len(levels))

输出

19102 21.419003 29.41519083 29.65


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5617679.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存