基于列表中的其他属性对属性求和

时间:2016-03-11 06:57:14

标签: python list count counter frequency

基本上我有一个带有数据的csv文件,如下所示:

['Store A', '2015-03-04', '00948', 'Red','A','AA']
['Store C', '2015-05-06', '00948', 'Blue','A','BB']
['Store B', '2015-07-08', '101130', 'Red','B','CC']
['Store A', '2015-09-10', '111011', 'Blue','C','DD']
['Store C', '2015-10-11', '101510', 'Red','A','EE']
['Store B', '2015-11-12', '101459', 'Red','B','FF']
['Store C', '2015-15-04', '01836', 'Blue','C','GG']
['Store B', '2015-30-05', '02201', 'Blue','A','HH']
['Store A', '2015-18-06', '04022', 'Red','C','II']
['Store C', '2015-07-07', '11056', 'Blue','B','JJ']
['Store C', '2015-08-05', '10149', 'Red','D','KK']
['Store A', '2015-10-04', '113569', 'Red','A','LL']
['Store B', '2015-12-03', '005410', 'Blue','C','MM']
['Store A', '2015-15-02', '053410', 'Blue','E','NN']
['Store A', '2015-16-04', '113410', 'Red','J','OO']

我想确定每个列表中出现“蓝色”一词的次数,这样输出基本上是“蓝色”一词的总和,给出第一个属性,即商店A,B和C,需要的输出应该是:

['Store A','Blue','2']
['Store B','Blue','2']
['Store c','Blue','3']

我的代码如下:

csvReader = csv.reader(open('count.csv','rb'), delimiter=',', quotechar='"')
for line in csvReader:
    print line.count('Blue')

显然结果是:

>>> 
0
0
0
.
.
.
.
0
0

我也试过了代码:

csvReader = csv.reader(open('count.csv','rb'), delimiter=',', quotechar='"')
for line in csvReader:
    count_blue= [[x, line.count('Blue')] for x in set(line)]
    print count_blue

它也没有给我所需的输出。什么似乎是我的错?谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

这看起来不像是一个CSV文件,它看起来像每行一个Python列表。使用literal_eval阅读并将其提供给Counter

from ast import literal_eval
from collections import Counter

blues = Counter()
with open("count.csv") as f:
    for line in f:
        ls = literal_eval(line)
        if ls[3] == 'Blue':
            blues[ls[0]] += 1

如果您想以所需的输出格式打印它:

for key in blues:
    print("['{}', 'Blue', {}]".format(key, blues[key]))

答案 1 :(得分:1)

我将假设您的CSV文件实际上是CSV文件。逗号是分隔符,quotechar是单引号char '

计算第0列中每个商店发生(从零开始)第3列的次数需要按列0对数据进行分组。一种方法是使用字典。 collections.defaultdict是一种字典,可以使用公共密钥轻松收集值列表。一旦你有了,你可以产生“蓝色”项目,或“红色”,或任何其他你可能有的计数。

import csv
from collections import defaultdict

d = defaultdict(list) 
with open('count.csv') as f:
    for row in csv.reader(f, quotechar="'"):
        d[row[0]].append(row[3])

    for k in sorted(d):
        print('{},{}'.format(k, d[k].count('Blue')))

<强>输出

Store A,2
Store B,2
Store C,3