【发布时间】:2021-05-13 15:12:42
【问题描述】:
我有一个包含 10 多列的 csv,它根据索引号进行分组。例如,
index othercolumn othercolumn2 sample hits othercolumn3
1 cccc bbbb dog 4 aaaa
1 cccc bbbb cat 1 aaaa
1 cccc bbbb cat 2 aaaa
2 cccc bbbb rat 1 aaaa
2 cccc bbbb dog 1 aaaa
3 cccc bbbb bird 1 aaaa
3 cccc bbbb rat 42 aaaa
3 cccc bbbb cat 3 aaaa
是否可以找到每个“组”的最大命中数(按索引)?我不太确定在没有最高命中的情况下该怎么做,比如样本 2,但现在这不是太重要。例如,所需的输出类似于,
For index 1, the highest hits are 4 for sample dog.
For index 2, the highest hits are 1 for sample rat.
For index 3, the highest hits are 42 for sample rat.
到目前为止,我已经使用 defaultdict 为每个组或索引创建了一个列表字典。但我似乎无法获得最高数量的点击并干净地打印出来。到目前为止,这就是我所拥有的。
from collections import defaultdict
import csv
groups = defaultdict(list)
with open('data.csv') as inputfile:
reader = csv.reader(inputfile)
next(reader, None) # skip the header row
for row in reader:
groups[row[1]].append([row[17], row[18]]) #row 1 is index, row 17 is my sample column, 18 is the hits column
print(groups)
不胜感激!
【问题讨论】:
标签: python python-3.x list dictionary