Possible reason 1: trying to create a jagged array
You may be creating an array from a list that isn't shaped like a multi-dimensional array:
Copynumpy.array([[1, 2], [2, 3, 4]]) # wrong!
Copynumpy.array([[1, 2], [2, [3, 4]]]) # wrong!
In these examples, the argument to numpy.array contains sequences of different lengths. Those will yield this error message because the input list is not shaped like a "box" that can be turned into a multidimensional array.
Possible reason 2: providing elements of incompatible types
For example, providing a string as an element in an array of type float:
Copynumpy.array([1.2, "abc"], dtype=float) # wrong!
If you really want to have a NumPy array containing both strings and floats, you could use the dtype object, which allows the array to hold arbitrary Python objects:
Copynumpy.array([1.2, "abc"], dtype=object)
Answer from Sven Marnach on Stack OverflowPossible reason 1: trying to create a jagged array
You may be creating an array from a list that isn't shaped like a multi-dimensional array:
Copynumpy.array([[1, 2], [2, 3, 4]]) # wrong!
Copynumpy.array([[1, 2], [2, [3, 4]]]) # wrong!
In these examples, the argument to numpy.array contains sequences of different lengths. Those will yield this error message because the input list is not shaped like a "box" that can be turned into a multidimensional array.
Possible reason 2: providing elements of incompatible types
For example, providing a string as an element in an array of type float:
Copynumpy.array([1.2, "abc"], dtype=float) # wrong!
If you really want to have a NumPy array containing both strings and floats, you could use the dtype object, which allows the array to hold arbitrary Python objects:
Copynumpy.array([1.2, "abc"], dtype=object)
The Python ValueError:
ValueError: setting an array element with a sequence.
Means exactly what it says, you're trying to cram a sequence of numbers into a single number slot. It can be thrown under various circumstances.
1. When you pass a python tuple or list to be interpreted as a numpy array element:
Copyimport numpy
numpy.array([1,2,3]) #good
numpy.array([1, (2,3)]) #Fail, can't convert a tuple into a numpy
#array element
numpy.mean([5,(6+7)]) #good
numpy.mean([5,tuple(range(2))]) #Fail, can't convert a tuple into a numpy
#array element
def foo():
return 3
numpy.array([2, foo()]) #good
def foo():
return [3,4]
numpy.array([2, foo()]) #Fail, can't convert a list into a numpy
#array element
2. By trying to cram a numpy array length > 1 into a numpy array element:
Copyx = np.array([1,2,3])
x[0] = np.array([4]) #good
x = np.array([1,2,3])
x[0] = np.array([4,5]) #Fail, can't convert the numpy array to fit
#into a numpy array element
A numpy array is being created, and numpy doesn't know how to cram multivalued tuples or arrays into single element slots. It expects whatever you give it to evaluate to a single number, if it doesn't, Numpy responds that it doesn't know how to set an array element with a sequence.
ValueError: setting an array element with a sequence.
machine learning - Getting 'ValueError: setting an array element with a sequence.' when attempting to fit mixed-type data - Data Science Stack Exchange
ValueError: setting an array element with a sequence
python - Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence? - Stack Overflow
Videos
I'm trying to integrate some ordinary differential equations but I need some of the parameters to be a cosine function of time. While testing the code, I keep getting the above value error. I also posted this to r/learningpython but this sub seems like it may be more helpful!
Here's the code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def vd(t):
return -(267 / 1440) * np.cos((2 * np.pi) / 365 * t) + (639 / 1440)
tmax = 2 * 365 # how long to run the system in days
t = np.arange(0.0, tmax, 1.0)
# define the constants
N = 3.295e8 # population of the US
theta = 0.8 # infectiousness
zeta = 0.75 # susceptibility
c = (N * 10 ** -5) / N # contact rate, depending on percentage of total population
alpha = theta * zeta * c
gamma = 0.1 # recovery rate, used often in class
rho = 0.2 # rate of loss of immunity
deltad = 0.1*vd(t) # rate of loss of Vitamin-D in body
# these are all the differential equations from simple SIR model
def deriv(y, t, alpha, gamma, rho):
S, I, R, D = y
dS = -alpha * I * S + rho * R
dI = alpha * I * S - gamma * I
dR = gamma * I - rho * R - rho * R * deltad
dD = deltad * (rho * R - S * L(t))
return dS, dI, dR, dD
# define some more initial conditions for integration
I0 = 1 # 1st person infected
R0 = 0 # 0 people recovered at first, obviously
S0 = N - I0 - R0
D0 = 0 # initial vitamin D in population, t=0 means January 1st
# initial conditions vector
y0 = S0, I0, R0, D0
ret = odeint(deriv, y0, t, args=(alpha, gamma, rho))
S, I, R, D = ret.T
Then I try to plot S, I, R, and D but that error pops up regarding the odeint line.
Those constants will probably change but I do need to input some stuff into dS, dI, dR, and dD that look like deltad and was hoping that someone on here with more python experience could help me.
Thank you!
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.
It's a pity that both of the answers analyze the problem but didn't give a direct answer. Let's see the code.
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):
# store the i-th result of
# function "func" in i-th item in kOUT
kOUT[i] = func(TempLake[i], Z)
The error shows that you set the ith item of kOUT(dtype:int) into an array. Here every item in kOUT is an int, can't directly assign to another datatype. Hence you should declare the data type of kOUT when you create it. For example, like:
Change the statement below:
kOUT = np.zeros(N + 1)
into:
kOUT = np.zeros(N + 1, dtype=object)
or:
kOUT = np.zeros((N + 1, N + 1))
All code:
import numpy as np
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, dtype=object)
for i in xrange(N):
kOUT[i] = func(TempLake[i], Z)
Hope it can help you.
From two different homeworks, dy(t, x) is a Jacobi matrix of a model function for a Gauss Newton algorithm.
Why does this function cause an error
def dy(t, x):
a1, a2, a3, a4, a5, a6, a7 = x
return np.array([1 / ( 1 + ((t - a6) / (a7 / 2))**2),
1,
t*1,
t**2,
t**3,
a1*(2*((t-a6)/(a7**2/4)) / (1+((t-a6)/(a7/2))**2)**2),
a1*(2/a7*((t-a6)/(a7/2)) / (1+((t-a6)/(a7/2))**2)**2)], dtype=float).T
x0 = np.array([2.06, 0.74, 8.92, -24.45, 17.84, 0.35, 0.1], dtype=float)
print("shape: ", dy(data[:,0],x0).shape)
print("dy:", dy(data[:,0], x0))
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (7,) + inhomogeneous part.
But this one does not?
def dy(t,x):
a, tau, omega, phi = x
return np.array([np.exp(-tau*t)*np.sin(omega*t+phi), #da/dt
-t*a*np.exp(-tau*t)*np.sin(omega*t+phi), #dtau/dt
t*a*np.exp(-tau*t)*np.cos(omega*t+phi), #domega/dt
a*np.exp(-tau*t)*np.cos(omega*t+phi)]).T #dphi/dt
x0 = np.array([1, 1, 3, 1],dtype=float)
dy(data[:,0], x0)
print("shape: ", dy(data[:,0],x0).shape)
Output: shape: (10, 4)