Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add all values in a CSV column in Python

Tags:

python

csv

These seems like something very simple, but search as I might I just can't get past it.

I have a CSV file like this:

Day,Event,Value
1,"Rent",500
7,"Wage Payments",1000

I wish to add up all of the numbers in the 'value' column. So far, my code is this:

cr = csv.reader(open("file.csv","rb"))

for row in cr:    
    print row

#print sum(Value)

How could I go about summing that value?

Thank you.

like image 314
samiles Avatar asked Dec 12 '22 02:12

samiles


2 Answers

Considering the first line of csv file is 'Day,Event,Value', you can use a generator expression with sum()

>>> cr = csv.reader(open("file.csv","rb"))
>>> cr.next()
>>> print sum(int(x[2]) for x in cr)
1500
like image 185
Ashwini Chaudhary Avatar answered Dec 28 '22 20:12

Ashwini Chaudhary


cr = csv.reader(open("file.csv","rb"))
cr.next() # to skip the header 

total = 0
for row in cr:  
   total += int(row[2])
   # possibly do other things with data/rows 

print total

There are more terse ways (e.g., list comprehension, or generator expressions) to do this, but this provides the basic idea and also lets you do other things with each line as needed (as pointed out by @MarkRansom too)

like image 22
Levon Avatar answered Dec 28 '22 20:12

Levon