从CSV文件中读取和汇总数据

时间:2014-04-27 06:05:36

标签: python python-2.7

我有一个格式如下的数据文件:

name,cost1,cost1,cost1,cost2,cost3,cost3,
X,2,4,6,5,6,8,
Y,0,3,6,5,4,6,
.
.
....

现在,我想要做的是将其转换为字典词典,以便

{'X', {'cost1': 4, 'cost2':5, 'cost3':7}},{'Y', {'cost1': 3, 'cost2':5, 'cost3':5}}....

其中每个键的值是数据文件的平均值。怎么可以这样做?

2 个答案:

答案 0 :(得分:1)

import csv
types = [str, float, float, float, float, float, float]                                            

with open('multientry.csv') as f:
    data = csv.reader(f, delimiter=',')
    headers = next(data)
    dofd = {}
    for r in data:
        r = tuple(convert(value) for convert, value in zip(types, r))
        dofd[r[0]] = {}
        dofd[r[0]]['cost1'] = (r[1]+r[2]+r[3])/3.
        dofd[r[0]]['cost2'] = r[4]
        dofd[r[0]]['cost3'] = (r[5]+r[6])/2.


print dofd

答案 1 :(得分:0)

基于@ cphlewis指示的更通用的版本:

load_data = csv.reader(open( "multientry.csv", "r" ))
header = next(load_data)
header = filter(bool,header)
categories = header
categories.pop(0)
categories = set(categories)
dofd={}
for row in load_data:
    row = filter(bool,tuple(value for  value in row))
    dofd[row[0]]={}
    for item in categories:
        val = [float(k) for k in [row[i+1] for i in [i for i, x in enumerate(header) if x == item]]]
        dofd[row[0]][item] = sum(val)/float(len(val))