【发布时间】:2020-02-14 05:47:31
【问题描述】:
考虑以下 CSV:
date,description,amount
14/02/2020,march contract,-99.00
15/02/2020,april contract,340.00
16/02/2020,march contract,150.00
17/02/2020,april contract,-100.00
我想做的是:
- 遍历所有行
- 总计
amounts 具有相同description的行 - 返回最后一行包含新计算的
amount
应用于上述示例,CSV 将如下所示:
16/02/2020,march contract,51.00
17/02/2020,april contract,240.00
到目前为止,我已经尝试将csv.reader()s 相互嵌套,但没有得到我想要的结果。
我想在没有任何库和/或模块的情况下实现这一目标。
这是我到目前为止的代码,其中first_row 是 CSV 中的每一行,second_row 是寻找匹配描述的迭代:
csv_reader = csv.reader(report_file)
for first_row in csv_reader:
description_index = 5
amount_index = 13
print(first_row)
for second_row in csv_reader:
if second_row is not first_row:
print(first_row[description_index] == second_row[description_index])
if first_row[description_index] == second_row[description_index]:
first_row[amount_index] = float(first_row[amount_index]) + float(second_row[amount_index])
【问题讨论】:
-
什么是 csv 对于 4 月合约也有多行?在那种情况下,你想要什么?仅三月还是仅四月?
-
嗯,cvs 模块是正确的起点。您能否向我们展示一些代码并确切告诉我们它是如何不符合您的要求的?
-
我编辑了我的问题以表明我希望将相同的效果应用于其中的所有各种合同
-
你会用熊猫吗?
-
用代码编辑了我的问题