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.1k16 gold badges89 silver badges129 bronze badges
asked Jan 12, 2011 at 21:58
7
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.1k16 gold badges89 silver badges129 bronze badges
answered Jan 12, 2011 at 23:51
Sven MarnachSven Marnach
556k115 gold badges923 silver badges825 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
142k95 gold badges407 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.5k7 gold badges46 silver badges83 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,24813 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,22812 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
![]()
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']
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
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: операнды не могли транслироваться вместе с фигурами
Introduction
In python, we have discussed many concepts and conversions. In this tutorial, we will be discussing the concept of setting an array element with a sequence. When we try to access some value with the right type but not the correct value, we encounter this type of error. In this tutorial, we will be discussing the concept of ValueError: setting an array element with a sequence in Python.
What is Value Error?
A ValueError occurs when a built-in operation or function receives an argument with the right type but an invalid value. A value is a piece of information that is stored within a certain object.
In python, we often encounter the error as ValueError: setting an array element with a sequence is when we are working with the numpy library. This error usually occurs when the Numpy array is not in sequence.
What Causes Valueerror: Setting An Array Element With A Sequence?
Python always throws this error when you are trying to create an array with a not properly multi-dimensional list in shape. The second reason for this error is the type of content in the array. For example, define the integer array and inserting the float value in it.
Examples Causing Valueerror: Setting An Array Element With A Sequence
Here, we will be discussing the different types of causes through which this type of error gets generated:
1. Array Of A Different Dimension
Let us take an example, in which we are creating an array from the list with elements of different dimensions. In the code, you can see that you have created an array of two different dimensions, which will throw an error as ValueError: setting an array element with a sequence.
import numpy as np print(np.array([[1, 2,], [3, 4, 5]],dtype = int))
Output:

Explanation:
- Firstly, we have imported the numpy library with an alias name as np.
- Then, we will be making the array of two different dimensions with the data type of integer from the np.array() function.
- The following code will result in the error as Value Error as we cannot access the different dimensions array.
- At last, you can see the output as an error.
Solution Of An Array Of A Different Dimension
If we try to make the length of both the arrays equal, then we will not encounter any error. So the code will work fine.
import numpy as np print(np.array([[1, 2, 5], [3, 4, 5]],dtype = int))
Output:

Explanation:
- Firstly, we have imported the numpy library with an alias name as np.
- Then, we will make the different dimension array into the same dimension array to remove the error.
- At last, we will try to print the output.
- Hence, you can see the output without any error.
Also, Read | [Solved] IndentationError: Expected An Indented Block Error
2. Different Type Of Elements In An Array
Let us take an example, in which we are creating an array from the list with elements of different data types. In the code, you can see that you have created an array of multiple data types values than the defined data type. If we do this, there will be an error generated as ValueError: setting an array element with a sequence.
import numpy as np print(np.array([2.1, 2.2, "Ironman"], dtype=float))
Output:

Explanation:
- Firstly, we have imported the numpy library with an alias name as np.
- Then, we will be making the array of two different data types with the data type as a float from the np.array() function.
- The array contains two data types, i.e., float and string.
- The following code will result in the error as Value Error as we cannot write the different data types values as the one data type of array.
- Hence, you can see the output as Value Error.
Solution Of Different Type Of Elements In An Array
If we try to make the data type unrestricted, we should use dtype = object, which will help you remove the error.
import numpy as np print(np.array([2.1, 2.2, "Ironman"], dtype=object))
Output:

Explanation:
- Firstly, we have imported the numpy library with an alias name as np.
- Then, if we want to access the different data types values in a single array so, we can set the dtype value as an object which is an unrestricted data type.
- Hence, you can see the correct output, and the code runs correctly without giving any error.
Also, Read | [Solved] TypeError: String Indices Must be Integers
3. Valueerror Setting An Array Element With A Sequence Pandas
In this example, we will be importing the pandas’ library. Then, we will be taking the input from the pandas dataframe function. After that, we will print the input. Then, we will update the value in the list and try to print we get an error.
import pandas as pd output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1']) print (output.loc['Project1', 'Sold Count']) output.loc['Project1', 'Sold Count'] = [400.0] print (output.loc['Project1', 'Sold Count'])
Output:

Solution Of Value Error From Pandas
If we dont want any error in the following code we need to make the data type as object.
import pandas as pd output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1']) print (output.loc['Project1', 'Sold Count']) output['Sold Count'] = output['Sold Count'].astype(object) output.loc['Project1','Sold Count'] = [1000.0,800.0] print(output)
Output:

Also, Read | How to Solve TypeError: ‘int’ object is not Subscriptable
4. ValueError Setting An Array Element With A Sequence in Sklearn
Sklearn is a famous python library that is used to execute machine learning methods on a dataset. From regression to clustering, this module has all methods which are needed.
Using these machine learning models over the 2D arrays can sometimes cause a huge ValueError in the code. If your 2D array is not uniform, i.e., if several elements in all the sub-arrays are not the same, it’ll throw an error.
Example Code –
import numpy as np from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC X = np.array([[-1, 1], [2, -1], [1, -1], [2]]) y = np.array([1, 2, 2, 1]) clf = make_pipeline(StandardScaler(), SVC(gamma='auto')) clf.fit(X, y)
Here, the last element in the X array is of length 1, whereas all other elements are of length 2. This will cause the SVC() to throw an error ValueError – Setting an element with a sequence.
Solution –
The solution to this ValueError in Sklearn would be to make the length of arrays equal. In the following code, we’ve changed all the lengths to 2.
import numpy as np from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC X = np.array([[-1, 1], [2, -1], [1, -1], [2, 1]]) y = np.array([1, 2, 2, 1]) clf = make_pipeline(StandardScaler(), SVC(gamma='auto')) clf.fit(X, y)
Also, Read | Invalid literal for int() with base 10 | Error and Resolution
5. ValueError Setting An Array Element With A Sequence in Tensorflow
In Tensorflow, the input shapes have to be correct to process the data. If the shape of every element in your array is not of equal length, you’ll get a ValueError.
Example Code –
import tensorflow as tf import numpy as np # Initialize two arrays x1 = tf.constant([1,2,3,[4,1]]) x2 = tf.constant([5,6,7,8]) # Multiply result = tf.multiply(x1, x2) tf.print(result)
Here the last element of the x1 array has length 2. This causes the tf.multiple() to throw a ValueError.
Solution –
The only solution to fix this is to ensure that all of your array elements are of equal shape. The following example will help you understand it –
import tensorflow as tf import numpy as np # Initialize two arrays x1 = tf.constant([1,2,3,1]) x2 = tf.constant([5,6,7,8]) # Multiply result = tf.multiply(x1, x2) tf.print(result)
6. ValueError Setting An Array Element With A Sequence in Keras
Similar error in Keras can be observed when an array with different lengths of elements are passed to regression models. As the input might be a mixture of ints and lists, this error may arise.
Example Code –
model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) # Compile the model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model model.fit(X, y, epochs=150, batch_size=10) >>> ValueError: setting an array element with a sequence.
Here the array X contains a mixture of integers and lists. Moreover, many elements in this array are not fully filled.
Solution –
The solution to this error would be flattening your array and reshaping it to the desired shape. The following transformation will help you to achieve it. keras.layers.Flatten and pd.Series.tolist() will help you to achieve it.
model = Sequential() model.add(Flatten(input_shape=(2,2))) model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) # Compile the model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model X = X.tolist() model.fit(X, y, epochs=150, batch_size=10)
Also, Read | How to solve Type error: a byte-like object is required not ‘str’
Conclusion
In this tutorial, we have learned about the concept of ValueError: setting an array element with a sequence in Python. We have seen what value Error is? And what is ValueError: setting an array element with a sequence? And what are the causes of Value Error? We have discussed all the ways causing the value Error: setting an array element with a sequence with their solutions. All the examples are explained in detail with the help of examples. You can use any of the functions according to your choice and your requirement in the program.
However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.
FAQs
1. How Does ValueError Save Us From Incorrect Data Processing?
We will understand this with the help of small code snippet:
while True:
try:
n = input("Please enter an integer: ")
n = int(n)
break
except ValueError:
print("No valid integer! Please try again ...")
print("Great, you successfully entered an integer!")
Input:
Firstly, we will pass 10.0 as an integer and then 10 as the input. Let us see what the output comes.
Output:

Now you can see in the code. When we try to enter the float value in place of an integer value, it shows me a value error which means you can enter only the integer value in the input. Through this, ValueError saves us from incorrect data processing as we can’t enter the wrong data or input.
2. We don’t declare a data type in python, then why is this error arrises in initializing incorrect datatype?
In python, We don’t have to declare a datatype. But, when the ValueError arises, that means there is an issue with the substance of the article you attempted to allocate the incentive to. This is not to be mistaken for types in Python. Hence, Python ValueError is raised when the capacity gets a contention of the right kind; however, it an unseemly worth it.
In this Python tutorial, we will be discussing the concept of setting an array element with a sequence, and also we will see how to fix error, Valueerror: Setting an array element with a sequence:
- An array of a Different dimension
- Setting an array Element with a sequence Pandas
- Valueerror Setting An Array Element with a Sequence in Sklearn
- Valueerror Setting An Array Element with a Sequence in Tensorflow
- Valueerror Setting An Array Element with a Sequence in np.vectorize
- Setting An Array Element with a Sequence in binary text classification
What is ValueError?
ValueError is raised when a function passes an argument of the correct type but an unknown value. Also, the situation should not be prevented by a more precise exception such as Index Error.
- In Python, the error as ValueError: Setting an array element with a sequence is when we are working with numpy library mostly. This error usually occurs when you are trying to create an array with a list that is not proper multi-dimensional in shape.
valueerror setting an array element with a sequence python
An array of a Different dimension
- In this example, we will create a numpy array from the list with elements of a different dimension which will throw an error as a value error setting an array element with a sequence
- Let us see and discuss this error and its solution
Here is the code of an array of a different dimension
import numpy as np
print(np.array([[4, 5,9], [ 7, 9]],dtype = int))
Explanation
- First we will import the numpy library.
- Then, we will create the array of two different dimension by using function np.array.
- Here is the Screenshot of the following given code

You can easily see the value error in the display. This is because the structure of the numpy array is not correct.
Solution
In this solution, we will declare the size and length of both the arrays equal and fix the value error.
import numpy as np
print(np.array([[4, 5,9], [ 4,7, 9]],dtype = int))
Here is the Screenshot of the following given code

This is how to fix value error by setting an array element with a sequence python.
Setting an array Element with a sequence Pandas
In this example, we will import the Python pandas module. Then we will create a variable and use the library pandas dataframe to assign the values. Now, we will print the input, Then it will update the value in the list and got a value error.
Here is the code of value error from pandas
import pandas as pd
out = pd.DataFrame(data = [[600.0]], columns=['Sold Count'], index=['Assignment'])
print (out.loc['Assignment', 'Sold Count'])
out.loc['Assignment', 'Sold Count'] = [200.0]
print (out.loc['Assignment', 'Sold Count'])
Explanation
The basic issue is that I would like to set a row and a column in the dataframe to a list .loc method is used and getting a value error
Here is the Screenshot of the following given code

Solution
In this solution, if you want to solve this error, You will create a non-numeric dtype as an object since it only stores numeric values.
Here is the Code
import pandas as pd
out = pd.DataFrame(data = [[600.0]], columns=['Sold Count'], index=['Assignment'])
print (out.loc['Assignment', 'Sold Count'])
out['Sold Count'] = out['Sold Count'].astype(object)
out.loc['Assignment','Sold Count'] = [1000.0,600.0]
print(out)
Here is the Screenshot of the following given code

This is how to fix the error, value error: setting an array element with sequence pandas.
Read Python Pandas Drop Rows Example
ValueError Setting An Array Element with a Sequence in Sklearn
- In this method, we will discuss an error with an iterable sequence in sklearn.
- Scikit-learn is a free machine learning module for Python. It features various algorithms like SVM, random forests, and k-neighbors, and it also generates Python numerical and scientific libraries like NumPy and SciPy.
- In machine learning models sometimes numpy array got a value error in the code.
- In this method, we can easily use the function SVC() and import the sklearn library.
Here is the code of value error setting an array element with a sequence
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X = np.array([[-3, 4], [5, 7], [1, -1], [3]])
y = np.array([4, 5, 6, 7])
clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
clf.fit(X, y)
Explanation
- In the above code, we will import a numpy library and sklearn. Now we will create an array X and y. The end element in the numpy array X is of length 1 whereas the other value has length2.
- This will display the result of a value error for an array element with the Sequence.
Here is the Screenshot of the following given code

Solution
- In this solution, we will change the size of the end element in a given array.
- we will give all the elements the same length.
Here is the code
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X = np.array([[-3, 4], [5, 7], [1, -1], [3,2]])
y = np.array([4, 5, 6, 7])
clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
clf.fit(X, y)
Here is the Screenshot of the following given code

This is how to fix the error, valueerror setting an array element with a sequence sklearn.
Read Remove character from string Python
Valueerror Setting An Array Element with a Sequence in Tensorflow
- In this method, we will learn and discuss an error with a sequence in Tensorflow.
- A Tensor’s shape is the rank of the Tensor module and the length of each dimension may not always be fully known. In tf.function the shape will only be partially known.
- In this method, if the shape of every element in a given numpy array is not equal to size you got an error message.
Here is the code of value error array element with a sequence in Tensorflow.
import tensorflow as tf
import numpy as np
x = tf.constant([4,5,6,[4,1]])
y = tf.constant([9,8,7,6])
res = tf.multiply(x,y)
tf.print(res)
Explanation
In this example, we will import a TensorFlow module then create a numpy array and assign values with different sizes of lengths. Now we create a variable and use the function tf. multiply.
Here is the Screenshot of the following given code

Solution
- In this solution, we will display and change the length of the end element in a given array.
- we will give all the values the same length and all the values are of equal shape.
Here is the Code
import tensorflow as tf
import numpy as np
x = tf.constant([4,5,6,4])
y = tf.constant([9,8,7,6])
res = tf.multiply(x,y)
tf.print(res)
Here is the Screenshot of the following given code

This is how to fix the error value error by setting an array element with a sequence TensorFlow.
valueerror setting an array element with a sequence np.vectorize
- In this method, we will learn and discuss an error with a sequence in np.vectorize
- The main purpose of np.vectorize is to transform functions that are not numpy aware into functions that can provide and operate on (and return) numpy arrays.
- In this example, the given function has been vectorized so that for every value in input array t, a numpy array is an output.
Here is the Code of the array element with a sequence in np.vectorize.
import numpy as np
def Ham(t):
d=np.array([[np.cos(t),np.sqrt(t)],[0,1]],dtype=np.complex128)
return d
print(Ham)
Explanation
In the above code, this error happens when there are more precise and conflicts with NumPy and python. If the dtype is not given the error may display.
Here is the Screenshot of the following given code

Solution
- In this method, the problem is that np.cos(t) and np.sqrt() compute the numpy arrays with the length of t, whereas the second row ([0,1]) maintains the same size.
- To use np.vectorize with your function, you have to declare the output type.
- In this method, we can easily use hamvec as a method.
Here is the Code
import numpy as np
def Ham(t):
d=np.array([[np.cos(t),np.sqrt(t)],[0,1]],dtype=np.complex128)
return d
HamVec = np.vectorize(Ham, otypes=[np.ndarray])
x=np.array([1,2,3])
y=HamVec(x)
print(y)
Here is the Screenshot of the following given code

This is how to fix the error, value error setting an array element with a sequence np.vectorize.
Valueerror Setting An Array Element with a Sequence in binary text classification with tfidfvectorizer
- In this section, we will learn and discuss an error with a sequence in binary text classification with a tfidfvectorizer.
- TF-IDF stands for Term Frequency Inverse Document Frequency. This method is a numerical statistic that measures the importance of the word in a document.
- A Scikit-Learn provides the result of the TfidfVectorizer.
- I am using pandas and scikit-learn to do binary text classification using text features encoded using TfidfVectorizer on a DataFrame.
Here is the code of binary text classification with tfidfvectorizer
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfVectorizer
data_dict = {'tid': [0,1,2,3,4,5,6,7,8,9],
'text':['This is the first.', 'This is the second.', 'This is the third.', 'This is the fourth.', 'This is the fourth.', 'This is the fourth.', 'This is the nintieth.', 'This is the fourth.', 'This is the fourth.', 'This is the first.'],
'cat':[0,0,1,1,1,1,1,0,0,0]}
df = pd.DataFrame(data_dict)
tfidf = TfidfVectorizer(analyzer='word')
df['text'] = tfidf.fit_transform(df['text'])
X_train, X_test, y_train, y_test = train_test_split(df[['tid', 'text']], df[['cat']])
clf = LinearSVC()
clf.fit(X_train, y_train)
Here is the Screenshot of the following given code

Solution
- Tfidfvectorizer returns a 2-Dimension array. You can’t set the column df[‘text’] to a matrix without up the dimensions.
- Try using only the training data in the fitness routine, and try expanding out the data and set to have more values.
Here is the code
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfVectorizer
data_dict = {'tid': [0,1,2,3,4,5,6,7,8,9],
'text':['This is the first.', 'This is the second.', 'This is the third.', 'This is the fourth.', 'This is the fourth.', 'This is the fourth.', 'This is the nintieth.', 'This is the fourth.', 'This is the fourth.', 'This is the first.'],
'cat':[0,0,1,1,1,1,1,0,0,0]}
df = pd.DataFrame(data_dict)
tfidf = TfidfVectorizer(analyzer='word')
df_text = pd.DataFrame(tfidf.fit_transform(df['text']).toarray())
X_train, X_test, y_train, y_test = train_test_split(pd.concat([df[['tid']],df_text],axis=1), df[['cat']])
clf = LinearSVC()
clf.fit(X_train, y_train)
Here is the Screenshot of the following given code

This is how to fix the error, Valueerror Setting An Array Element with a Sequence in binary text classification with tfidfvectorizer.
You may like the following Python tutorials:
- Groupby in Python Pandas
- How to use Pandas drop() function in Python
- Python NumPy Average with Examples
- Python NumPy absolute value
- Check if a list exists in another list Python
In this tutorial, we learned how to fix the error, value error setting an array element with a sequence python.
- An array of a Different dimension
- valueerror setting an array element with a sequence python
- Setting an array Element with a sequence Pandas
- ValueError Setting An Array Element with a Sequence in Sklearn
- Valueerror Setting An Array Element with a Sequence in Tensorflow
- Valueerror Setting An Array Element with a Sequence in np.vectorize
- Setting An Array Element with a Sequence in binary text classification

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.
In Python, if you are mainly working with numpy and creating a multi-dimensional array, you would have encountered valueerror: setting an array element with a sequence.
A ValueError occurs when a function receives an argument of the correct type, but the value of the type is invalid. In this case, if the Numpy array is not in the sequence, you will get a Value Error.
If you look at the example, the numpy array is 2-dimensional, but at the later stage, we have mixed with single-dimensional array also, and hence Python detects this as an inhomogeneous shape that means the structure of the array varies, and hence Python throws value error.
#Numpy array of different dimensions
import numpy as np
print(np.array([[[1, 2], [3, 4], [5, 6]], [[1],[2]]], dtype=int))
# Output
Traceback (most recent call last):
File "c:ProjectsTryoutslistindexerror.py", line 2, in <module>
print(np.array([[[1, 2], [3, 4], [5, 6]], [[1],[2]]], dtype=int))
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.
Solution – By creating the same dimensional array and having identical array elements in each array will solve the problem as shown below.
#Numpy array of same dimensions
import numpy as np
print(np.array([[[1, 2], [3, 4], [5, 6]]], dtype=int))
# Output
[[[1 2]
[3 4]
[5 6]]]
The other possibility where you get Value Error would be when you try to create an array with different types of elements; for instance, consider the below example where we have an array with float and string mixed, which again throws valueerror: could not convert string to float.
# Mutliple data type and dtype as float
import numpy as np
print(np.array([55.55, 12.5, "Hello World"], dtype=float))
# Output
Traceback (most recent call last):
File "c:ProjectsTryoutslistindexerror.py", line 2, in <module>
print(np.array([55.55, 12.5, "Hello World"], dtype=float))
ValueError: could not convert string to float: 'Hello World'
Solution – The solution of this is straightforward if you need either you declare only floating numbers inside an array or if you want both, then make sure that you change the dtype as an object instead of float as shown below.
# Changing the dtype as object and having multiple data type
import numpy as np
print(np.array([55.55, 12.5, "Hello World"], dtype=object))
# Output
[55.55 12.5 'Hello World']
Check out the below examples for more use cases and best practices while working with numpy arrays.
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
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
In python, you must be familiar with the NumPy package. And when you are creating multi-dimensional NumPy array then you will mostly get the Valueerror: Setting an Array Element with a Sequence error.
In this tutorial, you will know all the causes that lead to this error and how to solve this error.
What does setting an array element with a sequence mean in Python?
In python Valueerror: Setting an Array Element with a Sequence means you are creating a NumPy array of different types of elements in it. For example, mixing int with float or int or float with string. The other case when you will get this error is when you are creating a multiple-dimensional NumPy array. In addition, you are mixing with different dimensions. You will know how to solve this error in a simple way.
Cause 1: Mixing with different Array dimensions
The first case when you will get Valueerror: Setting an Array Element with a Sequence is creating an array with different dimensions or shapes. For example, if you will create a NumPy array of multi-dimension. One is a 2D array and the other is a 3D array.
import numpy as np
numpy_array = np.array([[1,2],[1,2,3]],dtype=int)
print(numpy_array)
When you will run the code you will get the value error.

Solution
The solution for this error is very simple. Just use the array of the same dimensions in a sequence. Instead of [1,2,3] or [1,2] use [1,2] or [1,2,3] respectively.
import numpy as np
numpy_array = np.array([[1,2],[1,2]],dtype=int)
print(numpy_array)
Output
[[1 2] [1 2]]
Cause 2: Elements of different type
The other cause for getting Valueerror is you are using different datatype elements for the NumPy array. For example, mixing string with int or float with int e.t.c.
import numpy as np
numpy_array = np.array([[1,2],["foo","foo"]],dtype=float)
print(numpy_array)

Solution
The solution for this case is also very simple. You should make sure that you should use elements of the same type.
import numpy as np
numpy_array = np.array([[1,2],[3,4]],dtype=int)
print(numpy_array)
Output
[[1 2] [3 4]]
The other solution for this error is that you should define the type of the NumPy array of the object type. Just write dtype=object.
import numpy as np
numpy_array = np.array([[1,2],["foo","foo"]],dtype=object)
print(numpy_array)
Output
[[1 2] ['foo' 'foo']]
END NOTES
Valueerror: Setting an Array Element with a Sequence error generally comes when you are creating a NumPy array using a different multi-dimensional array and different types of elements of the array. The above is the solutions for both cases.
I hope you have liked this tutorial. If you have any queries then you can contact us for more help.
Source:
Numpy array
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.
Something went wrong.
What is ValueError: setting an array element with a sequence?
While programming in Python, especially Numpy a library in Python, programmers encounter an error called ValueError: setting an array element with a sequence. This error usually occurs when the Numpy array is not in sequence.

Let us see the details of this error and also its solution:
Code
import numpy as np
np.array([[[1, 2], [3, 4], [5, 6]], [[1], [2,4], [3,6]]], dtype=int)
Output
Traceback (most recent call last):
File "pyprogram.py", line 2, in <module>
np.array([[[1, 2], [3, 4], [5, 6]], [[1], [2,4], [3,6]]], dtype=int)
ValueError: setting an array element with a sequence.
Explanation
We can see that when this code is executed, the ValueError is raised. This is because the structure of the array is not correct. This two-dimensional array has individual arrays that have two elements each,
[[[1, 2], [3, 4], [5, 6]], [[1], [2,4], [3,6]]], except [1].
Correct Code
import numpy as np
np.array([ [[1, 2], [3, 4], [5, 6]], [ [1,3], [2,4], [3,6] ] ], dtype=int)
Explanation
Here, no error is encountered as all the individual sequences or arrays have two elements each. So, Numpy can successfully create an array.
One of the most common errors encountered when working with Python arrays is valueerror: setting an array element with a sequence. This occurs when we access some value that has the right type but not the correct value.
For example, if we have an array of strings and try to set one of its elements with a number, then this error will occur. In this tutorial, we will learn about how to set array elemnts in sequence without getting an error in python, including how to fix it!
What is a ValueError?
A ValueError is an error that occurs when a built-in operation or function receives the right type of argument but with an invalid value. A value is defined as “a piece of information that is stored within a certain object.”
This means that there are values in just about everything! The content below will provide more detail on what this error entails and how to fix it for your program.
How to fix ValueError: setting an array element with a sequence, when working with the numpy library in Python.
The Numpy library is a powerful tool for scientific computing in Python. It provides fast and efficient operations on arrays of any dimension. However, sometimes we encounter ValueError when dealing with this library.
This error usually occurs when the Numpy array is not in sequence. In this blog post, I will discuss some ways to overcome these errors and avoid them altogether!
Python Error: Primarily Caused By Inappropriate Array Shapes
This is a common error that Python throws when you are trying to create an array with a not properly multi-dimensional list in shape. The second reason for this error is the type of content in the array.
For example, define the integer array and inserting the float value in it causes this error to be thrown. This blog post talks about what causes these errors and how to solve them by fixing your code or changing your data type.
What Causes This Error to Show Up?
This error is a very common one which many users come across when they are trying to download something from the internet. There are different causes for this error, and we will be discussing those in detail below:
-
The file you were trying to download got deleted or removed by the user who shared it with you.
- You have reached your bandwidth limit and exceeded your monthly quota of downloads.
- A firewall may have blocked the connection between your computer and the website where that file was located; therefore, blocking you from downloading it altogether.
- The file you were seeking was not found on that website.
-
A server connection problem happened between your browser and the website where that file is hosted; therefore, it could not be loaded or downloaded by anyone else either.
-
If this was an executable file, then you might have to check your anti-virus software for any virus or malware infection.
Error Raised When Setting Array Elements with Different Dimensions
When writing Python code, it is important to be mindful of the dimensions of the arrays that you are using. You can see an example below where we are trying to set an array element with a sequence, which will cause an error. This is because when you create arrays in Python, they need to have matching dimensions.
Code
import numpy as np
print(np.array([[2, 4, ], [3, 6, 9]],dtype = int))
Output
Solution
The key to writing error-free code is to make sure you use brackets. If we try to make the length of both arrays equal, then we will not encounter any error. So the code will work fine.
Code
import numpy as np
print(np.array([[2, 4, 6], [3, 6, 9]],dtype = int))
Output
Attempting to set different types element of an array with a sequence.
You might be wondering what an array is. An array is basically a list of values that are all the same type, which you can think of as something like a spreadsheet with rows and columns.
You can also think about it this way: if you were to represent your data in a table, then each column would be one data type (string, integer, float) and each row would have one value for that data type.
When we set an element in our array using Python’s sequence operator ‘,’ the order determines what goes on top for each row.
Code
import numpy as np
print(np.array([1.2, 0.2, "Hello"], dtype=float))
Output
Solution
One of the most common errors that Python users have is when they try to perform operations on mixed data types. If you are trying to add a string and an integer, for example, you will get this error:
The problem here is that Python doesn’t know what type your data should be. One way to fix this issue is by converting one of the values into another type so it matches the other value.
For instance, if we want to add a string and an integer then we can convert both numbers into strings before adding them together. This conversion can be done with either str() or int().
Code
import numpy as np
print(np.array([1.2, 0.2, "Hello"], dtype=object))
Output
Importing the pandas library: Input and Error
The pandas library is an open-source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.
To import this library, you need to use the following code:
Then input can be retrieved using the function DataFrame() which will return a list of cells in a two dimensional table with rows and columns that are labelled by index labels or name strings. To retrieve user input into the list we will type “input”. This will give us an error because there is no value named ‘input’.
Code
import pandas as pd
output = pd.DataFrame(data = [[600.0]], columns=['Sold Count'], index=['Project1'])
print (output.loc['Project1', 'Sold Count'])
output.loc['Project1', 'Sold Count'] = [300.0]
print (output.loc['Project1', 'Sold Count'])
Output
Solution
One of the most common programming errors is to forget to set the data type for an object and then trying to use it as if it were something else, such as a string or number. This can lead to many unexpected results that we needn’t worry about because we can easily fix this with one line of code!
Code
import pandas as pd
output = pd.DataFrame(data = [[600.0]], columns=['Sold Count'], index=['Project1'])
print (output.loc['Project1', 'Sold Count'])
output['Sold Count'] = output['Sold Count'].astype(object)
output.loc['Project1', 'Sold Count'] = [900.0, 600.0]
print (output)
Output
Also, it can be applied on other libraries like sklearn, keras, tensorflow, etc.
Conclusion
So what have we learned? We’ve seen that Value Error is a Python exception. It occurs when you set an array element with a sequence. In this tutorial, we explored the causes of Value Error: setting an array element with a sequence and how to solve them.
We also saw different ways to handle the error using examples which will be helpful for you in your programming journey
