开发者

integers when reading a csv file in python

开发者 https://www.devze.com 2023-03-23 16:16 出处:网络
I\'m trying to read a csv file in python, so that I can then find the average of the values in one of the columns using numpy.average.

I'm trying to read a csv file in python, so that I can then find the average of the values in one of the columns using numpy.average. My script looks like this:

import os
import numpy
import csv

listing = os.listdir('/path/to/directory/of/files/i/need')
os.chdir('/path/to/directory/of/files/i/need')


for file in listing[1:]:    
    r = csv.reader(开发者_开发问答open(file, 'rU'))   
    for row in r:
        if len(row)<2:continue
        if float(row[2]) <=0.05:
            avg = numpy.average(float(row[2]))
    print avg

but I keep on getting the error ValueError: invalid literal for float(). The csv reader seems to be reading the numbers as string, and won't allow me to convert it to a float. Any suggestions?


Judging by the comments, your program is running into problems with the headers.

Two solutions of this are to use r.next(), which skips a line, before your for loop, or to use the DictReader class. The advantage of the DictReader class is that you can treat each row as a dictionary instead of a tuple, which may make for more readability in some cases, but you do have to pass the list of headers to it in the constructor.


change:

float(row[2])

to:

float(row[2].strip("'\""))
0

精彩评论

暂无评论...
验证码 换一张
取 消