python - 如何计算条件列中值的频率?

标签 python csv dictionary counting

我有一个包含以下数据的 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 和条件,它正确显示了特定列的项目频率。但我想要它基于一个条件。如何才能做到这一点?

最佳答案

您可以使用 collections.defaultdict 创建嵌套字典:

from io import StringIO
import csv
from collections import defaultdict

mystr = StringIO("""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""")

d = defaultdict(lambda: defaultdict(int))

# replace mystr with open('file.csv', 'r')
with mystr as fin:
    for item in csv.DictReader(fin):
        d[int(item['TaskId'])][int(item['Attr. 1'])] += 1
        d[int(item['TaskId'])][item['Attr. 2']] += 1
        d[int(item['TaskId'])][item['Attr. 3']] += 1

print(d)

defaultdict({123: defaultdict(int, {23: 3, 'twothree': 2, 'xyx': 2,
                                    'four': 1, 'lor': 1}),
             352: defaultdict(int, {34: 1, 'some': 1, 'lkj': 1}),
             456: defaultdict(int, {23: 1, 'four': 1, 'pop': 1})})

然后像普通字典一样进行迭代:

for k, v in d.items():
    print('TaskId: {0}'.format(k))
    for a, b in v.items():
        print('{0}: {1} times'.format(a, b))

结果:

TaskId: 123
23: 3 times
twothree: 2 times
xyx: 2 times
four: 1 times
lor: 1 times
TaskId: 456
23: 1 times
four: 1 times
pop: 1 times
TaskId: 352
34: 1 times
some: 1 times
lkj: 1 times

关于python - 如何计算条件列中值的频率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50861253/

相关文章:

java - 如何知道所有内容是否都已附加到 csv 中?

javascript - 如何在 JavaScript 中映射 "map"的键/值对?

python - 无法连接到雪花

python - 如何在Python中对相关的字符串列表和数字列表进行排序?

python - 如何使用 CSV 作为 Tensorflow 神经网络的输入数据?

javascript - 如何跳过或忽略标题上方的行?

java - 计算字符串标记时忽略空格

python - 如何只打印按字母顺序嵌套在列表、字典中的内部字典的键?

Python 游标返回行数而不是行数

python - 正则表达式用于匹配不具有相同单词出现在另一个关键字之前的关键字