Matthew Clark
Matthew Clark

Reputation: 31

Error uploading using csv reader:

I am trying to do some data manipulation and analysis using python. I am new to python and I am having some troubles loading data using the csv library of functions. My code:

import csv

out = open("data1.csv","rb")
data = csv.reader(out)
data = [row for row in data]
x = data[:,0]

Produces the error:

Traceback (most recent call last):
  File "/home/matthew/NumericalAnalysis.py", line 12, in <module>
    x = data[:,0]
TypeError: list indices must be integers, not tuple

From what I understand this could be in part due to the fact that the list was saved as strings instead of floats. If so can someone help me with this?

Upvotes: 1

Views: 57

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122322

You are passing in a tuple to the data slice:

data[:,0]

The comma makes :,0 a tuple, albeit one that wouldn't be able to stand on it's own. It is legal Python syntax, but it is called an extended slice. Numpy supports these for matrices, but regular python lists do not.

If you wanted to select all the first columns of all rows (which is what your extended slice would do for a numpy two-dimensional matrix), do so when reading the CSV:

data = [row[0] for row in data]

This picks the first column of each row supplied by the csv.reader() object.

Upvotes: 2

bwind
bwind

Reputation: 715

You can't use commas in indices. If you want an element from data, or a slice, proceed as follows:

x = data[:4]
x = data[2]

Upvotes: 2

Related Questions