为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Python 3.7 汇总数据?

如何使用 Python 3.7 汇总数据?

慕妹3242003 2021-10-26 18:03:31
我有我转换成字典的 CSV 文件。字典中的一行看起来像这样:-OrderedDict([('MVA', '10072672'), ('Code', 'F5'), ('Tbk Mnth', '01-Dec-16'), ('Branch', 'W0S'), ('Make', 'VOLKSWAGENRSA'), ('Status', 'RISK'), ('Price', '111200.27')])我试图对“价格”列中的值求和,但 n = 0。我做错了什么?另外,总结不同代码的最有效方法是什么?import csvlinecount = 0with open(r'C:\Users\anthony\Documents\Test\Data.csv') as file:    reader = csv.DictReader(file)    for row in reader:        print(row)        code = (row["Code"])        if code == 'F5':            linecount += 1    print(linecount)    n = sum([item['Price'] for item in reader])    print(n)
查看完整描述

2 回答

?
长风秋雁

TA贡献1757条经验 获得超7个赞

reader是一个迭代器。通过迭代它,你可以消耗它的值。如果您需要保留这些值,那么您必须存储在其他地方。最简单的方法是从迭代器创建一个列表,然后迭代这个列表。


例如。


rows = list(reader)


for row in rows:

   ...


n = sum([item['Price'] for item in rows])

但是,价格将是一个字符串而不是一个浮点数。因此,您将列表理解将它们转换为浮点数。例如。float(item['Price'])


查看完整回答
反对 回复 2021-10-26
?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

一个问题是你不能重复阅读器两次。


模块中的defaultdict类collections对于对项目进行分组很方便。在这里,我们将Prices(Decimal为了精确而转换为s)收集到一个列表字典中,然后将它们相加。


import csv

import decimal

import collections


# Defaultdicts are handy in that they never have nonexistent keys;

# if you access an nonexistent key, the constructor (`list` here)

# is invoked.


prices_by_code = collections.defaultdict(list)


with open(r'Data.csv') as file:

    reader = csv.DictReader(file)

    for row in reader:

        price = row.get('Price')

        code = row.get('Code')

        if code and price:

            prices_by_code[code].append(decimal.Decimal(price))


# By this time,  `prices_by_code` looks approximately like

# {"5": [1, 2, 3], "8": [4, 5, 6]}


for code, prices in sorted(prices_by_code.items()):

    print(code, sum(prices))


查看完整回答
反对 回复 2021-10-26
  • 2 回答
  • 0 关注
  • 164 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号