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.
Mateen Ulhaq
23.9k18 gold badges95 silver badges132 bronze badges
asked Jan 12, 2011 at 21:58
1
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:
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.
Possible reason 2: providing elements of incompatible types
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)
Mateen Ulhaq
23.9k18 gold badges95 silver badges132 bronze badges
answered Jan 12, 2011 at 23:51
Sven MarnachSven Marnach
568k117 gold badges935 silver badges835 bronze badges
0
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.
answered Nov 25, 2017 at 4:40
Eric LeschinskiEric Leschinski
145k95 gold badges412 silver badges332 bronze badges
0
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.
answered Apr 2, 2018 at 19:20
Aaditya UraAaditya Ura
11.9k7 gold badges49 silver badges87 bronze badges
0
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)
answered Aug 11, 2018 at 6:41
Adam LiuAdam Liu
1,27813 silver badges17 bronze badges
1
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.
answered Mar 14, 2018 at 17:56
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)
answered Feb 28, 2019 at 18:54
Max KleinerMax Kleiner
1,3761 gold badge13 silver badges14 bronze badges
1
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
«
answered Jul 2, 2020 at 14:55
1
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?.
answered Aug 3, 2020 at 18:41
questionto42questionto42
6,6224 gold badges52 silver badges86 bronze badges
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)
answered Feb 2 at 15:44
In this article, we will discuss how to fix ValueError: setting array element with a sequence using Python.
Error which we basically encounter when we using Numpy library is ValueError: setting array element with a sequence. We face this error basically when we creating array or dealing with numpy.array.
This error occurred because of when numpy.array creating array with given value but the data-type of value is not same as data-type provided to numpy.
Steps needed to prevent this error:
- Easiest way to fix this problem is to use the data-type which support all type of data-type.
- Second way to fix this problem is to match the default data-type of array and assigning value.
Method 1: Using common data-type
Example : Program to show error code:
Python
import
numpy
array1
=
[
1
,
2
,
4
, [
5
, [
6
,
7
]]]
Data_type
=
int
np_array
=
numpy.array(array1, dtype
=
Data_type)
print
(np_array)
Output:
File “C:UserscomputersDownloadshe.py”, line 13, in <module>
np_array = numpy.array(array1,dtype=Data_type);
ValueError: setting an array element with a sequence.
We can fix this error if we provide the data type which support all data-type to the element of array:
Syntax:
numpy.array( Array ,dtype = Common_DataType );
Example: Fixed code
Python
import
numpy
array1
=
[
1
,
2
,
4
, [
5
, [
6
,
7
]]]
Data_type
=
object
np_array
=
numpy.array(array1, dtype
=
Data_type)
print
(np_array)
Output:
[1 2 4 list([5, [6, 7]])]
Method 2: By matching default data-type of value and Array
Example: Program to show error
Python
import
numpy
array1
=
[
"Geeks"
,
"For"
]
Data_type
=
str
np_array
=
numpy.array(array1, dtype
=
Data_type)
np_array[
1
]
=
[
"for"
,
"Geeks"
]
print
(np_array)
Output:
File “C:UserscomputersDownloadshe.py”, line 15, in <module>
np_array[1] = [“for”,”Geeks”];
ValueError: setting an array element with a sequence
Here we have seen that this error is cause because we are assigning array as a element to array which accept string data-type. we can fix this error by matching the data-type of value and array and then assign it as element of array.
Syntax:
if np_array.dtype == type( Variable ): expression;
Example: Fixed code
Python
import
numpy
array1
=
[
"Geeks"
,
"For"
]
Data_type
=
str
np_array
=
numpy.array(array1, dtype
=
Data_type)
Variable
=
[
"for"
,
"Geeks"
]
if
np_array.dtype
=
=
type
(Variable):
np_array[
1
]
=
Variable
else
:
print
(
"Variable value is not the type of numpy array"
)
print
(np_array)
Output:
Variable value is not the type of numpy array ['Geeks' 'For']
Last Updated :
10 Feb, 2022
Like Article
Save Article
17 авг. 2022 г.
читать 1 мин
Одна ошибка, с которой вы можете столкнуться при использовании Python:
ValueError : setting an array element with a sequence.
Эта ошибка обычно возникает, когда вы пытаетесь втиснуть несколько чисел в одну позицию в массиве NumPy.
В следующем примере показано, как исправить эту ошибку на практике.
Как воспроизвести ошибку
Предположим, у нас есть следующий массив NumPy:
import numpy as np
#create NumPy array
data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Теперь предположим, что мы пытаемся втиснуть два числа в первую позицию массива:
#attempt to cram values '4' and '5' both into first position of NumPy array
data[0] = np.array([4,5])
ValueError : setting an array element with a sequence.
Ошибка говорит нам, что именно мы сделали неправильно: мы попытались установить один элемент в массиве NumPy с последовательностью значений.
В частности, мы попытались втиснуть значения «4» и «5» в первую позицию массива NumPy.
Это невозможно сделать, поэтому мы получаем ошибку.
Как исправить ошибку
Способ исправить эту ошибку — просто присвоить одно значение первой позиции массива:
#assign the value '4' to the first position of the array
data[0] = np.array([4])
#view updated array
data
array([ 4, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Обратите внимание, что мы не получаем никаких ошибок.
Если мы действительно хотим присвоить два новых значения элементам массива, нам нужно использовать следующий синтаксис:
#assign the values '4' and '5' to the first two positions of the array
data[0:2] = np.array([4, 5])
#view updated array
data
array([ 4, 5, 3, 4, 5, 6, 7, 8, 9, 10])
Обратите внимание, что первые два значения в массиве были изменены, а все остальные значения остались прежними.
Дополнительные ресурсы
В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:
Как исправить KeyError в Pandas
Как исправить: ValueError: невозможно преобразовать число с плавающей запятой NaN в целое число
Как исправить: ValueError: операнды не могли транслироваться вместе с фигурами
This guide teaches you how to fix the common error ValueError: setting array element with a sequence in Python/NumPy.
This error occurs because you have elements of different dimensions in the array. For example, if you have an array of arrays and one of the arrays has 2 elements and the other has 3, you’re going to see this error.
Let me show you how to fix it.
Cause 1: Mixing Arrays of Different Dimensions
One of the main causes for the ValueError: setting array element with a sequence is when you’re trying to insert arrays of different dimensions into a NumPy array.
For example:
import numpy as np arr = np.array([[1,2], [1,2,3]], dtype=int) print(arr)
Output:
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.
If you take a closer look at the error above, it states clearly that there’s an issue with the shape of the array. More specifically, the first array inside the arr has 2 elements ([1,2]) whereas the second array has 3 elements ([1,2,3]). To create an array, the number of elements of the inner arrays must match!
Solution
Let’s create arrays with an equal number of elements.
import numpy as np numpy_array = np.array([[1, 2], [1, 2]], dtype=int) print(numpy_array)
Output:
[[1 2] [1 2]]
This fixes the issue because now the number of elements in both arrays is the same—2.
Cause 2: Trying to Replace a Single Array Element with an Array
Another reason why you might see the ValueError: setting array element with a sequence is if you try to replace a singular array element with an array.
For example:
import numpy as np arr = np.array([1, 2, 3]) arr[0] = np.array([4, 5]) print(arr)
Output:
ValueError: setting an array element with a sequence.
In this piece of code, the issue is you’re trying to turn the first array element, 1, into an array [4,5]. NumPy expects the element to be a single number, not an array. This is what causes the error
Solution
Make sure to add singular values into the array in case it consists of individual values. Don’t try to replace a value with an array.
For example:
import numpy as np arr = np.array([1, 2, 3]) arr[0] = np.array([4]) print(arr)
Output:
[4 2 3]
Thanks for reading. Happy coding!
Read Also
Python Tips and Tricks
About the Author
-
I’m an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts
If you try to put a sequence of more than one element in the place of an array element, you will raise the error: ValueError: setting an array element with a sequence.
To solve this error, ensure that each element in the array is of consistent length and that you do not have a sequence in place of a single element.
The error can also happen if you attempt to create a numpy array with elements of different data-type than that specified with the dtype parameter. To solve this error, you can set the dtype of the numpy array to object.
This tutorial will go through the error in detail and how to solve it with the help of code examples.
Table of contents
- What is a ValueError?
- Example #1: Setting An Array Element With A Sequence in Numpy
- Solution #1: Changing dtype to object
- Solution #2: Fixing List Structure
- Example #2: Setting An Array Element With A Sequence in Numpy
- Solution
- Example #3: Setting An Array Element With A Sequence in Scikit-Learn
- Solution
- Summary
What is a ValueError?
In Python, a value is the information stored within a particular object. You will encounter a ValueError in Python when you use a built-in operation or function that receives an argument with the right type but an inappropriate value.
Example #1: Setting An Array Element With A Sequence in Numpy
Let’s look at an example where we create a numpy array using a list of values. We can select the data type of the numpy array using the dtype parameter. In this example, we will set the data type to an integer. Let’s look at the code:
import numpy as np
arr = [2, 4, 5, [10, [12, 14]]]
data_type=int
np_arr = np.array(arr, dtype=data_type)
print(np_arr)
Let’s run the code to see the result:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
5 data_type=int
6
---≻7 np_arr = np.array(arr, dtype=data_type)
8
9 print(np_arr)
ValueError: setting an array element with a sequence.
The first error is a TypeError, which we throw because the int() method expects certain data types, but it received a list. The cause of the TypeError is the ValueError. The ValueError occurs because NumPy interprets [10, [12, 14]] as a list, but the data type of the numpy array to create is int. The array can only accept integers as elements.
Solution #1: Changing dtype to object
To solve this error, we can set the data type to object; the array will then support all data types, including list. Let’s look at the revised code:
import numpy as np
arr = [2, 4, 5, [10, [12, 14]]]
data_type=object
np_arr = np.array(arr, dtype=data_type)
print(np_arr)
Let’s run the code to see the result:
[2 4 5 list([10, [12, 14]])]
We have a NumPy object array, which contains references to numpy.str_ objects. Let’s look at the type of the elements in the array:
for i in np_arr:
print(type(i))
≺class 'numpy.str_'≻
≺class 'numpy.str_'≻
≺class 'numpy.str_'≻
≺class 'numpy.str_'≻
We can still manipulate the integer elements as integers and the list element as a list
val = np_arr[0]
val_sq = val ** 2
print(val_sq)
4
lst = np_arr[3]
print(lst[0])
10
Solution #2: Fixing List Structure
Another way to resolve this is to fix the structure of the original list. If we define the list as a two-dimensional nested list, where each list has the same length, we can pass it to the np.array() method. Let’s look at the revised code:
import numpy as np
arr = [[2, 4, 5], [10, 12, 14]]
data_type=int
np_arr = np.array(arr, dtype=data_type)
print(np_arr)
Let’s run the code to see the result:
[[ 2 4 5]
[10 12 14]]
The result is a two-dimensional numpy array, which is we can treat as a matrix. For further reading on matrices, go to the articles:
- How to Multiply Two Matrices in Python
- How to Find the Transpose of a Matrix in Python
If the dimensions of the nested list are different, the array creation will fail if the data type is not object.
import numpy as np
arr = [[2, 4], [10, 12, 14]]
data_type=int
np_arr = np.array(arr, dtype=data_type)
print(np_arr)
ValueError: setting an array element with a sequence.
To fix this, we either need to ensure the elements are of consistent length or set the data type of the array to object. The resultant array will contain numpy.str_ objects that each refer to a list:
import numpy as np
arr = [[2, 4], [10, 12, 14]]
data_type=object
np_arr = np.array(arr, dtype=data_type)
print(np_arr)
[list([2, 4]) list([10, 12, 14])]
Example #2: Setting An Array Element With A Sequence in Numpy
Let’s look at an example where we try to assign a sequence to an element of an array that only accepts a specific data type.
import numpy as np
arr = ["Python", "is", "really", "fun", "to", "learn"]
data_type = str
np_arr = np.array(arr, dtype=data_type)
np_arr[1] = ["Python", "is"]
In the above code, we attempt to assign a list of strings to a single element in the numpy array, which has the data type str. Let’s run the code to see what happens:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
----≻ 1 np_arr[1] = ["Python", "is"]
ValueError: setting an array element with a sequence
The error occurs because the array expects a string value, but it receives a list with multiple strings.
Solution
To solve this error, we need to set the data type of the numpy array to object. Let’s look at the revised code.
import numpy as np
arr = ["Python", "is", "really", "fun", "to", "learn"]
data_type = object
np_arr = np.array(arr, dtype=data_type)
np_arr[1] = ["Python", "is"]
Let’s run the code to get the result:
['Python' list(['Python', 'is']) 'really' 'fun' 'to' 'learn']
The updated array now has a list object as the first element, and the rest are string objects.
If we want the numpy array to be one specific data type, we need to use an if statement. The if statement will only assign an element if the object has the same data type as the numpy array. Let’s look at the revised code:
import numpy as np
arr = ["Python", "is", "really", "fun", "to", "learn"]
data_type = str
np_arr = np.array(arr, dtype=data_type)
variable = ["Python", "is"]
if np_arr.dtype == type(variable):
np_arr[1] = variable
else:
print(f'Variable value does not match the type of the numpy array {data_type}')
print('Array: ', np_arr)
The if statement checks if the object we want to assign to the element has the same data type as the numpy array. If it does, then the assignment happens. Otherwise, we get a print statement telling us there is a mismatch in data types. Let’s run the code to see what happens:
Variable value does not match the type of the numpy array ≺class 'str'≻
Array: ['Python' 'is' 'really' 'fun' 'to' 'learn']
Example #3: Setting An Array Element With A Sequence in Scikit-Learn
Let’s look at another common source of the ValueError. This example will attempt to create a Scikit-Learn pipeline to fit a classifier with some training data.
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
# Training data
X = np.array([[-1, 1], [2, -1], [1, -1], [2]])
# Labels
y = np.array([1, 2, 2, 1])
# Pipeline
clf = make_pipeline(StandardScaler(), MLPClassifier())
# Fitting
clf.fit(X, y)
Let’s run the code to see what happens:
ValueError: setting an array element with a sequence.
We raise the ValueError because the fourth element in the array is a single value, whereas the other three elements contain two values. Therefore, the array has mismatching dimensions. If you want to manipulate multi-dimensional arrays in Python, the elements must be of consistent length.
Solution
To solve this error, we must ensure all elements have the same length. Let’s look at the revised code:
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
# Training data
X = np.array([[-1, 1], [2, -1], [1, -1], [2, 1]])
#Labels
y = np.array([1, 2, 2, 1])
#Pipeline
clf = make_pipeline(StandardScaler(), MLPClassifier())
# Fitting
clf.fit(X, y)
The fourth element now has two values like the rest of the elements. This code will run without any errors.
Summary
Congratulations on reading to the end of this tutorial! The error ValueError: setting an array element with a sequence occurs when you attempt to set an element to a sequence that contains more than one item. The common sources of the error are
- Attempting to create an array with a nested list of mixed dimensions
- Creating an array with a given value but the data-type of the value is not the same as the data-type of the numpy array.
To create a multi-dimensional array, ensure your elements have consistent lengths. Otherwise, if you do not need consistent element lengths, you can set the data type of the numpy array to object.
Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.
Have fun and happy researching!