Search code examples
pythoncsvsum

Python: How to calculate sum of floats on csv


I'm starting to learn Python. How do I calculate the sum (float) of a certain column on csv file?

This is what I've done so far, but my code is not giving me the total of 'amount' (column):

giftFile = open('input.v0.small.csv')
giftReader = csv.reader(giftFile)
giftData = list(giftReader)

for row in giftReader:
    if len(row)>0:
        giftData += row['amount']

print('row 0:' + str(giftData[0]))
print("row 1's dollar value: " + str(giftData[1]))

Sample from csv-file:

date,amount,vendor,not sure,who,category
3/11/17, 100.00,"99 PLEDGCharlie S 99PLEDGES.COMAZ",2,Bob Smith,charity
3/11/17, 3.27,"CAFE BEARYUM ORO VALLEY AZ"

Solution

  • You could try:

    import csv
    from math import fsum
    
    with open('input.v0.small.csv', 'r') as file:
        result = fsum(
            float(d['amount']) if d['amount'].strip() else 0
            for d in csv.DictReader(file) if d['amount']
        )
    
    • Assumption: csv-file contains a header row and the column you want to sum up is named amount.
    • Using a DictReader instead of a reader to be able to fetch the amount by column name.
    • Using fsum instead of sumto avoid loss of precision.

    Result for file

    date,amount,vendor,not sure,who,category
    3/11/17, 100.00,"99 PLEDGCharlie S 99PLEDGES.COMAZ",2,Bob Smith,charity
    3/11/17, 3.27,"CAFE BEARYUM ORO VALLEY AZ"
    

    is

    103.27
    

    Result for file

    date,amount,vendor,not sure,who,category
    3/11/17, 100.00,"99 PLEDGCharlie S 99PLEDGES.COMAZ",2,Bob Smith,charity
    
    
    3/11/17, 3.27,"CAFE BEARYUM ORO VALLEY AZ"
    

    is

    103.27