Why do the following code samples:
np.array([[1, 2], [2, 3, 4]])
np.array([1.2, "abc"], dtype=float)
all give the following error?
ValueError: setting an array element with a sequence.
Why do the following code samples:
np.array([[1, 2], [2, 3, 4]])
np.array([1.2, "abc"], dtype=float)
all give the following error?
ValueError: setting an array element with a sequence.
You may be creating an array from a list that isn't shaped like a multi-dimensional array:
numpy.array([[1, 2], [2, 3, 4]]) # wrong!
numpy.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.
For example, providing a string as an element in an array of type float
:
numpy.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:
numpy.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:
import 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:
x = 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.
In my case , I got this Error in Tensorflow , Reason was i was trying to feed a array with different length or sequences :
example :
import tensorflow as tf
input_x = tf.placeholder(tf.int32,[None,None])
word_embedding = tf.get_variable('embeddin',shape=[len(vocab_),110],dtype=tf.float32,initializer=tf.random_uniform_initializer(-0.01,0.01))
embedding_look=tf.nn.embedding_lookup(word_embedding,input_x)
with tf.Session() as tt:
tt.run(tf.global_variables_initializer())
a,b=tt.run([word_embedding,embedding_look],feed_dict={input_x:example_array})
print(b)
And if my array is :
example_array = [[1,2,3],[1,2]]
Then i will get error :
ValueError: setting an array element with a sequence.
but if i do padding then :
example_array = [[1,2,3],[1,2,0]]
Now it's working.
for those who are having trouble with similar problems in Numpy, a very simple solution would be:
defining dtype=object
when defining an array for assigning values to it. for instance:
out = np.empty_like(lil_img, dtype=object)
In my case, the problem was another. I was trying convert lists of lists of int to array. The problem was that there was one list with a different length than others. If you want to prove it, you must do:
print([i for i,x in enumerate(list) if len(x) != 560])
In my case, the length reference was 560.
In my case, the problem was with a scatterplot of a dataframe X[]:
ax.scatter(X[:,0],X[:,1],c=colors,
cmap=CMAP, edgecolor='k', s=40) #c=y[:,0],
#ValueError: setting an array element with a sequence.
#Fix with .toarray():
colors = 'br'
y = label_binarize(y, classes=['Irrelevant','Relevant'])
ax.scatter(X[:,0].toarray(),X[:,1].toarray(),c=colors,
cmap=CMAP, edgecolor='k', s=40)
When the shape is not regular or the elements have different data types, the dtype
argument passed to np.array only can be object
.
import numpy as np
# arr1 = np.array([[10, 20.], [30], [40]], dtype=np.float32) # error
arr2 = np.array([[10, 20.], [30], [40]]) # OK, and the dtype is object
arr3 = np.array([[10, 20.], 'hello']) # OK, and the dtype is also object
``
In my case, I had a nested list as the series that I wanted to use as an input.
First check: If
df['nestedList'][0]
outputs a list like [1,2,3]
, you have a nested list.
Then check if you still get the error when changing to input df['nestedList'][0]
.
Then your next step is probably to concatenate all nested lists into one unnested list, using
[item for sublist in df['nestedList'] for item in sublist]
This flattening of the nested list is borrowed from How to make a flat list out of list of lists?.
In my case, it was a version problem. I got the error for numpy version = 1.24.1. But when I downgraded to 1.21.6, the problem was fixed.
python -m pip install numpy==1.21.6
The error is because the dtype argument of the np.array function specifies the data type of the elements in the array, and it can only be set to a single data type that is compatible with all the elements. The value "abc" is not a valid float, so trying to convert it to a float results in a ValueError. To avoid this error, you can either remove the string element from the list, or choose a different data type that can handle both float values and string values, such as object.
numpy.array([1.2, "abc"], dtype=object)
A common reason this error occurs is when you want to change the dtype of an array from object
to int
/float
etc using an astype()
call. There could be two cases:
The most common case is when the array is jagged. In this case, the "inner" array probably needs to be flattened before changing the dtype.
import numpy as np
arr = np.array([1,2, [3,4]], dtype=object)
arr.astype(int) # <--- ValueError: setting an array element with a sequence.
# flatten array
out = []
for x in arr:
if isinstance(x, (list, np.ndarray, tuple)):
out.extend(x)
else:
out.append(x)
arr = np.array(out) # <--- OK
Another common case is when an object
dtype array's "inner" arrays are not read properly, which causes this error even if the shapes and dtypes are seemingly a-OK.
For example in the following case, the "inner" arrays of arr
have the same shape (and have the same dtype as well), so we don't have the jagged array problem, yet when calling astype(int)
, we get the error in the title.
arr = np.array([1, 2], dtype=object)
arr[:2] = [[10], [20]]
arr # array([list([10]), list([20])], dtype=object)
arr.astype(int) # <--- ValueError: setting an array element with a sequence.
In this case, convert arr
into a list and convert to an ndarray later; or just stack()
it.
np.array(arr.tolist()) # <--- OK
np.stack(arr) # <--- OK
This error commonly occurs when a pandas column that contained lists/ndarrays are attempted to be converted into a numpy ndarray using astype()
. In other words, it occurs if you want to make the following conversion using astype()
.
In this case, instead of astype()
, use stack()
or convert to a list and cast to an ndarray.
import pandas as pd
s = pd.Series([[1,2], [3,4]])
s.astype(int) # <--- ValueError: setting an array element with a sequence.
s.to_numpy().astype(int) # <--- ValueError: setting an array element with a sequence.
np.array(s.tolist()) # <--- OK
np.stack(s) # <--- OK
np.where()
/np.nonzero()
returns a tupleAnother common example where this error occurs is when you want to assign the values returned from np.where()
to an array. However, np.where()
when only the condition is passed returns a tuple (same with np.nonzero()
), which leads to this error, for the same reason explained in Eric Leschinski's answer. In this case, assign only the relevant value from the tuple (in the example below, that is the first item in the tuple).
arr = np.array([1, 2, 3])
arr[:3] = np.where(arr>0) # <--- ValueError: ...
arr[:3] = np.where(arr>0)[0] # <--- OK
arr[:3] = np.nonzero(arr>0)[0] # <--- OK