我有一个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))
我没有提供row
和条件,而是提供了data
,它正确地显示了特定列的项频率。但我要有条件的。如何做到这一点?你知道吗
如果你不想使用熊猫,可以用字典轻松地做到:
或者,也可以不用python轻松完成:
使用熊猫可能更快:
可以使用
collections.defaultdict
创建嵌套字典:然后像普通字典一样迭代:
结果:
相关问题 更多 >
编程相关推荐