Meelfan Bmfp
Meelfan Bmfp

Reputation: 605

compare sum of column values in python

I have a csv file loaded in a python object. 15 of the columns contains binary values. I have several thousands rows.

I want to count the sum of the binary values of each of the columns and sort the result ascendingly.

I only made it to:

sum1=sum(products['1'])
sum2=sum(products['2'])
sum3=sum(products['3'])
....
...
sum15=sum(products['15'])

and process the result manually. Is there a programmatic way to achieve this?

Upvotes: 0

Views: 610

Answers (2)

Tony Vu
Tony Vu

Reputation: 4361

How about this:

sorted_sum = sorted([sum(products[i]) for i in range(1, 16)])

sorted_sum is the sorted list of column sums. However, I believe the index should run from 0 to 14, not 1 to 15.

Upvotes: 1

khelili miliana
khelili miliana

Reputation: 3822

you will find the solution here :

with open("file.csv") as fin:
headerline = fin.next()
list_sum_product=[]
for i in range(15):
    total = 0
    for row in csv.reader(fin):
        total += int(row[i])
    list_sum_product.append(total)
print sorted(list_sum_product)

Upvotes: 1

Related Questions