我已经记录了一些步骤以帮助澄清问题:
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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)