Python: getting data from CSV file into lists

Status
Not open for further replies.

Soriak

Ars Legatus Legionis
13,069
Subscriptor
I have written a function to plot data and run a regression from two lists - so far, so good. Now, I'm trying to turn two columns from my CSV file into lists, so that I can run my function on them. Alas, I have not had any luck.

Currently, the best I can do is to get the columns into an array:

Code:
numpy.loadtxt(DATA+"ces.csv", dtype=int, skiprows=1, delimiter=",", unpack=true, usecols=(0,1))
which simply looks like this:
Code:
array([[641702, 641732, 641762, ..., 657902, 657942, 657952],
       [     4,      4,      1, ...,      4,      7,      1]])
Now, however, I can't seem to get these nested lists (I guess that's what they are?) into their own lists so that I can run my function on them. Is there maybe a better way to get these columns into lists?

Also, the CSV file has a header, which I simply excluded with skiprows. It would be particularly neat if the columns were automatically named after those headers. That would, presumably, allow me to simply run my function on, say, ("SIZE","INCOME"), rather than digging up the column numbers for them.

Thoughts and help are much appreciated. :)
 

Soriak

Ars Legatus Legionis
13,069
Subscriptor
QuantumET":33tiuj3y said:
Why don't you try the CSV support from the included libraries?, before rolling your own.
Why do it easy when there's a hard way? :)

Actually, that was the first thing I tried, but I couldn't get it to work. Since you suggested it, I went back and spent more time with it... and look at that, it works! Thanks for the guidance! :)
 

norton_I

Ars Tribunus Angusticlavius
6,172
Subscriptor++
By the way, the result of numpy.loadtxt is *not* a list of lists, but a numpy 2-D array. You can index individual rows and columns by using the array slice notation:

Code:
x = numpy.loadtxt(DATA+"ces.csv", dtype=int, skiprows=1, delimiter=",", unpack=True, usecols=(0,1))
myfunc(x[0,:], x[1,:])

You can also assign by unpacking:

Code:
(x, y) = numpy.loadtxt(DATA+"ces.csv", dtype=int, skiprows=1, delimiter=",", unpack=True, usecols=(0,1))
myfunc(x, y)

Anyway, the csv methods are the right answer if you want lists, use this if you want numpy arrays.
 
Status
Not open for further replies.