【问题标题】:How to summarise Data Using Python 3.7?如何使用 Python 3.7 汇总数据?
【发布时间】:2019-02-01 08:49:25
【问题描述】:

我有一个 CSV 文件,可以转换成字典。字典中的一行如下所示:-

OrderedDict([('MVA', '10072672'), ('Code', 'F5'), ('Tbk Mnth', '01-Dec-16'), ('Branch', 'W0S'), ('Make', 'VOLKSWAGENRSA'), ('Status', 'RISK'), ('Price', '111200.27')])

我试图对“价格”列中的值求和,但 n = 0。我做错了什么?另外,对不同代码求和的最有效方法是什么?

import csv
linecount = 0
with 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)

【问题讨论】:

  • 您已经使用循环到达阅读器的末尾:for row in reader 这就是没有剩余数据的原因
  • 你得到什么错误?程序会崩溃还是给出错误的输出?如果是后一种情况,你想实现什么,你实际得到什么?我认为您将sum 放在错误的位置,因为它无法访问reader 数据,但请确认。
  • @gonczor OP 提到了这个问题;他们得到 n = 0,所以这是错误的输出。

标签: python python-3.x


【解决方案1】:

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

collections 模块中的defaultdict 类可以方便地对项目进行分组。 在这里,我们将Prices(为了精确而转换为Decimals)收集到一个列表字典中,然后对它们求和。

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))

【讨论】:

  • 当我运行您的代码时,我收到以下错误:-prices_by_code[row["Code"]].append(decimal.Decimal(item["Price"])) NameError: name 'item'未定义
  • 糟糕,我的意思是row["Price"]
  • 试过了!现在我收到以下错误:prices_by_code[row["Code"]].append(decimal.Decimal(row["Price"])) KeyError: 'Price'
  • 每一行实际上都有一个Price 列吗?
  • (修改了代码以添加对这种情况的保护。)
【解决方案2】:

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

例如。

rows = list(reader)

for row in rows:
   ...

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

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

【讨论】:

    猜你喜欢
    • 2011-12-05
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 2018-04-23
    相关资源
    最近更新 更多