finding the length of a portion of a csv file in python

Viewed 94

I'm trying to get the average of part of a column in a csv file but I haven't been able to find the length. I noticed that when I run len it's counting the amount of characters and not the length from 2021-2003 (len should be 18).

*Note: This is for a class and will not be using pandas

import csv

with open('C:/Users/lblortz/Desktop/LakeMead.csv', newline='') as csv_file:
    list_name = csv.reader(csv_file, delimiter=',')

  index=0
    total=0.0
    count=0.0

    for YEAR, AVGELEVATION, AVGCONTENT, AVGINFLOW, AVGOUTFLOW, AVGHIGHTEMP, AVGLOWTEMP, AVGWATERTEMP in list_name:

        if index != 0:
            if int(YEAR)>=2003:
                print(len(list_name))
                total= float(AVGELEVATION) + total     
        index+=1
        
    count=total/len(list_name)
    print("average is",count)

1 Answers

Welcome to SO. Your code is pretty good as is.

For finding the average of total over a number of years, yeah, you've got an issue in that here:

count=total/len(YEAR)

it looks like you are equating len(YEAR) with "all the cells (rows) in the YEAR column", but you've found out that it really means "the length of characters in the value stored in the variable YEAR", and you set that value in your loop—so it's the length of characters of the last year your loop counted.

The quick fix for this is to keep track of how many years have been counted:

index=0
total=0.0
count=0.0
years=[]  # create an empty list and add years to it as they are counted
...

        if int(YEAR) >= 2003:
            years.append(YEAR)
            ...

count=total/len(years)

For dealing with the CSV in general, I also recommend this small change...

your index counter

It looks like index only exists to say whether you've iterated past the header. You can manually read the first row (the header) and do nothing with it (discard it) like this:

list_name=csv.reader(csv_file)
next(list_name)
...

next() is the Python way of manually iterating an iterable, which is what csv.reader() makes.

Related