How to Fix: ValueError: setting an array element with a sequence
Last Updated :
10 Feb, 2022
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:\Users\computers\Downloads\he.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:\Users\computers\Downloads\he.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']
Share your thoughts in the comments
Please Login to comment...