Reputation: 71
I have a csv where I need to count the total number for each category:
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]
I need it to count each occurrence of TRUE for the if-condition so that it will look like:
[A01] : 3
instead of:
1 1 1
I currently have:
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()
Upvotes: 0
Views: 2477
Reputation: 121
To add on to Kevin's answer, you can also use a dictionary to increment the counts for multiple categories.
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
Upvotes: 0
Reputation: 76194
Initialize counts
before the loop begins, increment it when your condition succeeds, and only print it after the loop ends.
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
Note that counts =+ 1
and counts += 1
do very different things. The first means "assign positive one to counts" and the second one means "increment count
's value by one"
Upvotes: 1