gpt4 book ai didi

python - 在 Python 中检查 CSV 是否存在类似值

转载 作者:行者123 更新时间:2023-12-01 00:02:46 28 4
gpt4 key购买 nike

考虑以下 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

我想做的是:

  • 迭代所有行
  • 具有相同描述的行的数量总数
  • 返回包含新计算的金额的最后一行

应用于上面的示例,CSV 将如下所示:

16/02/2020,march contract,51.00
17/02/2020,april contract,240.00

到目前为止,我已经尝试将 csv.reader() 嵌套在彼此内部,但没有得到我想要的结果。

我想在没有任何库和/或模块的情况下实现这一目标。

这是我到目前为止的代码,其中 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])

最佳答案

这会起作用:

import csv
uniques = {} # dictionary to store key/value pairs


with open(report_file, newline='') as f:
reader = csv.reader(f, delimiter=',')
next(reader, None) # skip header row
for data in reader:
date = data[0]
description = data[1]
if description in uniques:
cumulative_total = uniques[description][0]
uniques[description] = [cumulative_total+float(data[2]), date]
else:
uniques[description] = [float(data[2]), date]

# print output
for desc, val in uniques.items():
print(f'{val[0]}, {desc}, {val[1]}')

我知道您要求一个没有 pandas 的解决方案,但如果您使用它,您会节省很多时间:

df = pd.read_csv(report_file)

totals = df.groupby(df['description']).sum()
print(totals)

关于python - 在 Python 中检查 CSV 是否存在类似值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60220688/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com