1

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?

0

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

3 Comments

Umm, I believe that you can use commas in indices, at least using numpy:>>> import numpy as npy >>> x = npy.mat([[1,2,3],[4,5,6],[6,7,8]]) >>> x[0,0] 1 >>>
@user2457869: Exactly, numpy supports those, but regular python lists don't.
Ok, thanks for that, but now I'm having tab delimiting errors: out = open("data1.csv","rb") rawdata = csv.reader(out) rawdata = [row for row in rawdata] data = npy.mat(rawdata) time = data[:,0] IndexError: invalid index
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.