Newbie - converting csv files to arrays in NumPy

Robert Kern robert.kern at gmail.com
Tue Jan 9 15:36:47 EST 2007


oyekomova wrote:
> I would like to know how to convert a csv file with a header row into a
> floating point array without the header row.

Use the standard library module csv. Something like the following is a cheap and
cheerful solution:


import csv
import numpy

def float_array_from_csv(filename, skip_header=True):
    f = open(filename)
    try:
        reader = csv.reader(f)
        floats = []
        if skip_header:
            reader.next()
        for row in reader:
            floats.append(map(float, row))
    finally:
        f.close()

    return numpy.array(floats)

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco




More information about the Python-list mailing list