栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611556.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号