繁体   English   中英

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

[英]get value of one column by another column in csv file python

我有这样的 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.33
C: sum = 5, avg = 5.00
B: sum = 13, avg = 6.50

也可以使用标准的 Python 字典来完成。 解决方案非常相似:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM