MEhsan
MEhsan

Reputation: 2324

Computing the Sum of Values in a Column

I am trying to write a python program that computes the sum of values from csv data file. The csv file simply contains three columns and three rows containing numeric data. The csv data file looks like the following:

Colum1,Colum2,Colum3
1,2,3
1,2,3
1,2,3   

I am having problem with my python code to compute the sum. Somehow it is not computing the sum of all the values of Colum1, rather it just prints the two rows/values of 'Colum1'

import csv
file = open('data.csv')
rows = csv.DictReader(file)
for r in rows:
    print sum([float(r['Colum1'])])

Any thought how to solve this problem?

Thank you!

Upvotes: 0

Views: 2778

Answers (1)

yurib
yurib

Reputation: 8147

You should sum over all rows and not just one:

import csv
with open('data.csv') as f:
    rows = csv.DictReader(f)
    print sum(float(r['Colum1']) for r in rows)

Also, it is a good practice to close opened files, the with .. as .. syntax takes care of this

Upvotes: 2

Related Questions