Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to total CSV column?

Tags:

python

csv

I want to total a column in a CSV file using the python script below. However, I'm getting the following error.

invalid literal for int() with base 10: '7.3'

What is wrong with my script?

import csv

cr = csv.reader(open("companylist.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
like image 660
josh Avatar asked May 04 '26 06:05

josh


2 Answers

Instead of creating the total variable and incrementing it, you can do it in one shot via a Generator Expression.

import csv

with open("book1.csv", "rb") as csv_file:
    reader = csv.DictReader(csv_file)
    total = sum(float(row["column_name_here"]) for row in reader)
print(total)
like image 94
Eric Avatar answered May 05 '26 21:05

Eric


You are trying converting non-integer string value to int with your statement

total += int(row[2]) # possibly do other things with data/rows

use float() instead of it:

total += float(row[2]) # possibly do other things with data/rows
like image 28
MarianD Avatar answered May 05 '26 19:05

MarianD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!