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)
To put a sequence or another numpy array into a numpy array, Just change this line:
kOUT=np.zeros(N+1)
to:
kOUT=np.asarray([None]*(N+1))
Or:
kOUT=np.zeros((N+1), object)
KOUT[i] is a single element of a list. But you are assigning a list to this element. your func is generating a list.
You can try the expand
option in Series.str.split('seperator', expand=True)
.
By default expand
is False
.
expand
: bool, defaultFalse
Expand the splitted strings into separate columns.
- If
True
, return DataFrame/MultiIndex expanding dimensionality.- If
False
, return Series/Index, containing lists of strings.
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.
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.vectorize(func)(TempLake,Z)
This works too , instead of looping , just vectorize however read below notes from the scipy documentation : https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html
The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.
If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs. The results of this call will be cached if cache is True to prevent calling the function twice. However, to implement the cache, the original function must be wrapped which will slow down subsequent calls, so only do this if your function is expensive.
I believe python arrays just admit values. So convert it to list:
kOUT = np.zeros(N+1)
kOUT = kOUT.tolist()
Source: Stackoverflow.com