views:

34

answers:

2

I am trying to populate data from some csv files into a numpy array with the following code:

PreExArray=zeros([len(TestIDs),numColumns],float)

for row in reader:
    if row[1] =='PreEx10SecondsBEFORE':
        PreExArray[(j-1),0]=[row[2]]

However, the last line of code above throws the following error:

ValueError: setting an array element with a sequence.

So I printed out the contents of row[2] as follows:

print 'row[2] is:  ',row[2]

This produced:

row[2] is: 0.780083333333

So the contents of row[2] are not a sequence as the error message indicates. Instead, the contents are a number.

Therefore, I used to following code to put the contents of row[2] into a variable, then populate PreExArray[(j-1),0] with the contents of that variable, and then print out the contents of that variable:

jones = row[2]
PreExArray[(j-1),0]=jones
print 'PreExArray[(j-1),0] is:  ',PreExArray[(j-1),0]

The result is:

PreExArray[(j-1),0] is: 0.780083333333

So, putting row[2] into a variable solves the problem. But this is really sloppy code if I have to put it into a variable every time.

Can anyone show me how to fix the code so that it does not throw an error when I type something a lot simpler, like PreExArray[(j-1),0]=[row[2]] ?

===========================================================================================

OK. I re-wrote the code, and now it is throwing a new error. The new code is as follows:

PreExArray=zeros([len(TestIDs),numColumns],float) 

for row in reader: 
    if row[1] =='PreEx10SecondsBEFORE': 
        PreExArray[(j-1),0]=row[1]
        PreExArray[(j-1),1]=row[2]

This revised code now throws the following error message:

PreExArray[(j-1),0]=row[1]
ValueError: setting an array element with a sequence.

However, when I comment out PreExArray[(j-1),0]=row[1] as follows (#PreExArray[(j-1),0]=row[1]), the subsequent lines run without throwing an error.

Can anyone tell me how to edit this so that it does not continue to throw this error?

+1  A: 

You should just have:

PreExArray[(j-1),0]=row[2]

That is, the right hand side should NOT be put into a length-1 list.

Vincent Marchetti
A: 

It looks like your row variables are from a spreadsheet, and the first index values are row labels (strings). As has been pointed out, you cannot store this data in a numpy array of datatype 'float'.

The error message you get arises from the fact that to numpy, a string looks like a sequence (probably because it supports a len attribute.)

If you want to save the row labels in order to reconstruct a spreadsheet importable file, with the new values you calculate, you will have to store them in a separate list.

Vincent Marchetti