gpt4 book ai didi

python - python获取csv文件中一列的另一列的值

转载 作者:太空宇宙 更新时间:2023-11-03 17:21:41 25 4
gpt4 key购买 nike

我的 csv 文件如下:

ID        Value      Amount 
---- ------- -------
A 3 2
A 4 4
B 3 6
C 5 5
A 3 2
B 10 1

我想要“ID”列“值”或“金额”列的总和。我想要的输出是,对于“A”,它应该给出与 A 相关的所有值的总和,即 [3+4+3]。

我的代码:

import csv
file = open(datafile.csv)
rows=csv.DictReader(file)
summ=0.0
count=0
for r in rows:
summ=summ+int(r['Value'])
count=count+1
print "Mean for column Value is: ",(summ/count)
file.close()

最佳答案

您可以使用 listdefaultdict 按 ID 列对数据进行分组。然后使用 sum() 生成总计。

from collections import defaultdict

with open('datafile.csv') as f:
d = defaultdict(list)
next(f) # skip first header line
next(f) # skip second header line
for line in f:
id_, value, amount = line.split()
d[id_].append((int(value), int(amount)))

# sum and average of column Value by ID
for id_ in d:
total = sum(t[0] for t in d[id_])
average = total / float(len(d[id_]))
print('{}: sum = {}, avg = {:.2f}'.format(id_, total, average))

输入数据的输出:

A: sum = 10, avg = 3.33C: sum = 5, avg = 5.00B: sum = 13, avg = 6.50

It can also be done with a standard Python dictionary. The solution is very similar:

with open('datafile.csv') as f:
d = {}
next(f) # skip first header line
next(f) # skip second header line
for line in f:
id_, value, amount = line.split()
d[id_] = d.get(id_, []) + [(int(value), int(amount))]

# sum and average of column Value by ID
for id_ in d:
total = sum(t[0] for t in d[id_])
average = total / float(len(d[id_]))
print('{}: sum = {}, avg = {:.2f}'.format(id_, total, average))

关于python - python获取csv文件中一列的另一列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33072677/

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