adding values from a csv column and getting the mean. beginner help

Mark Lawrence breamoreboy at yahoo.co.uk
Wed Dec 11 20:34:30 CET 2013


On 11/12/2013 19:10, brian cleere wrote:
> I know the problem is with the for loop but don't know how to fix. Any help with explanation would be appreciated.
>
> #!/bin/env python
> import csv

You never use the csv module.

> import sys
>
> if len(sys.argv) < 3:
>      print('Please specify a filename and column number: {} [csvfile] [column]'.format(sys.argv[0]))
>      sys.exit(1)
>
> filename = sys.argv[1]
> column = int(sys.argv[2])
>
> for line in filename() , column ():

You're trying to loop around the filename and the column, you need to 
open the file and loop around that.

>      elements = line.strip().split(',')

Please don't do this when you've got the csv module to do things for you.

>      values.append(int(elements[col]))

Where did values come from?  Is it col or column, please make your mind up?

So let's stick things together.  Something like.

values = []
with open(filename) as csvfile:
     valuereader = csv.reader(csvfile)
     for row in valuereader:
         values.append(int(row[column]))

>
> csum = sum(values)
> cavg = sum(values)/len(values)
> print("Sum of column %d: %f" % (col, csum))
> print("Avg of column %d: %f" % (col, cavg))

I like consistency, new style formatting here, old style above, still if 
it works for you.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list