user1419224 - 1 year ago 363
Python Question

# Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

Why do I get this error message? ValueError: setting an array element with a sequence. Thank you

``````Z=np.array([1.0,1.0,1.0,1.0])

def func(TempLake,Z):
A=TempLake
B=Z
return A*B

Nlayers=Z.size
N=3
TempLake=np.zeros((N+1,Nlayers))

kOUT=np.zeros(N+1)
for i in xrange(N):
kOUT[i]=func(TempLake[i],Z)
``````

You're getting the error message

``````ValueError: setting an array element with a sequence.
``````

because you're trying to set an array element with a sequence. I'm not trying to be cute, there -- the error message is trying to tell you exactly what the problem is. Don't think of it as a cryptic error, it's simply a phrase. What line is giving the problem?

``````kOUT[i]=func(TempLake[i],Z)
``````

This line tries to set the `ith` element of `kOUT` to whatever `func(TempLAke[i], Z)` returns. Looking at the `i=0` case:

``````In [39]: kOUT[0]
Out[39]: 0.0

In [40]: func(TempLake[0], Z)
Out[40]: array([ 0.,  0.,  0.,  0.])
``````

You're trying to load a 4-element array into `kOUT[0]` which only has a float. Hence, you're trying to set an array element (the left hand side, `kOUT[i]`) with a sequence (the right hand side, `func(TempLake[i], Z)`).

Probably `func` isn't doing what you want, but I'm not sure what you really wanted it to do (and don't forget you can usually use vectorized operations like A*B rather than looping in numpy.) That should explain the problem, anyway.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download