我有一个csv,我需要计算每个类别的总数:
New_Cell[2] Category I need to count
1 [A01]
1 [A01]
0 [A01]
1 [A01]
0 [A02]
1 [A02]
1 [A02]
2 [A02]
1 [A02]
我需要它来计算if条件的每次出现TRUE,以便它看起来像:
[A01] : 3
而不是:
1 1 1
我目前有:
A01 = "[A01] Officials"
data_out = open("mentees_all_attributes.csv", "rU")
reader = csv.reader(data_out)
next(reader,None)
for line in reader:
cells = line
new_cell = cells[0], cells[6], cells[7], cells[8], cells[9], cells[10] # name, # of participation, primary occupation/industry, secondary occupation/industry
if int(new_cell[1]) > 0: #Isolate all the participants with more than 0
primary = new_cell[2]
if primary == A01:
if True:
counts =+ 1
print counts
data_out.close()
答案 0 :(得分:1)
在循环开始之前初始化counts
,在条件成功时递增它,并且只在循环结束后打印它。
counts = 0
for line in reader:
cells = line
new_cell = cells[0], cells[6], cells[7], cells[8], cells[9], cells[10] # name, # of participation, primary occupation/industry, secondary occupation/industry
if int(new_cell[1]) > 0: #Isolate all the participants with more than 0
primary = new_cell[2]
if primary == A01:
counts += 1
print counts
请注意counts =+ 1
和counts += 1
做的事情非常不同。第一种方法"将正数分配给计数"第二个意味着"将count
的值增加一个"
答案 1 :(得分:0)
要添加凯文的答案,您还可以使用字典来增加多个类别的计数。
categories = {}
counts = 0
for line in reader:
cells = line
new_cell = cells[0], cells[6], cells[7], cells[8], cells[9], cells[10]
if int(new_cell[1]):
primary = new_cell[2]
if primary:
if primary not in categories.keys():
categories[primary] = 0
categories[primary] += 1
for k,v in categories.items():
print k, v