python计算来自csv

时间:2017-04-10 06:36:28

标签: python csv

我试图从csv文件(有两个cols [' customer' ,'类别'])以下列格式输入dict,

foodict = {
   'customer' : 'cust1' , 
   'categories' : { 'cat1' : 50, 'cat2' : 55 } , 
   'contribution' : { 
                     'cat1' : cat1/(cat1+cat2) ,
                     'cat2' : cat2/(cat1+cat2) 
                    }
       }
到目前为止,我已经这样了,但却无法实现这一目标。我试图在纯python中使用它而不使用任何其他数据库。

c = {}

for i in customer:
    for j in category:
        for k in db:
           count = 0
           if k['customer'] == i and k['category'] == j:
               count += 1
               if not i in c.keys():
                   c[i] = {'category' : j , 'counts' : count}
               else:
                   pass

1 个答案:

答案 0 :(得分:0)

@len:

这满足了我的要求,但是有没有任何有效的分组方法,就像我们在excel中那样得到计数贡献为'在数据透视表中按行值汇总

foo_dict = {}
for name in cust:
    for j in category:
        foo_dict[name] = {
                    'total' : int(sum(1 for i in db if i['cust'] == name)),
                    'lob' : {pro : int(sum(1 for i in db if i['cust'] == name and i['category'] == pro)) for pro in category},
                    'conts' : {pro : round(
                        float(
                            sum(1 for i in db if i['cust'] == name and i['category'] == pro)/int(sum(1 for i in db if i['cust'] == name))),2) for pro in category},
                    'samples' : {pro : round(
                        float(
                            sum(1 for i in db if i['cust'] == name and i['category'] == pro)/int(sum(1 for i in db if i['cust'] == name))),0) for pro in category}
                  }