【发布时间】:2018-11-24 10:53:18
【问题描述】:
我有一个 csv 文件,其数据如下:
TaskId | Attr. 1 | Attr. 2 | Attr. 3
123 23 twothree xyx
123 23 four lor
456 23 four pop
123 23 twothree xyx
352 34 some lkj
我想根据任务 ID 生成具有属性和频率的字典(甚至只是打印)。
预期输出:
For task id 123,
23: 3 times
four: 1 times
twothree: 2 times
xyx: 2 times
lor: 1 time
我尝试了以下方法:
import csv
from collections import Counter
from itertools import imap
from operator import itemgetter
with open('task.csv') as f:
data = csv.reader(f)
for row in data:
if row[0] == '123':
cn = Counter(imap(itemgetter(2), row))
for t in cn.iteritems():
print("{} appears {} times".format(*t))
但它没有工作。在
Counter(imap(itemgetter(2), row))
我提供了data 而不是row 和条件,它正确显示了特定列的项目频率。但我想要它基于一个条件。如何才能做到这一点?
【问题讨论】:
-
发布预期输出
-
你可以考虑使用 groupby docs.python.org/2/library/itertools.html#itertools.groupby
-
@RomanPerekhrest 发布了预期的输出
标签: python csv dictionary counting