Table of Contents
This article discusses the generation of error “setting an array element with a sequence”, how it can occur, what causes this error and how to fix it.
This error is generated while using the numpy library while working with numpy arrays.
Numpy is a python library that is used to deal with large numbers and matrices. It consists of high level mathematical functions to deal with numbers and functions.
Why does ValueError : setting an array element with a sequence occur?
The error setting an array element with a sequence occurs when the datatype of all the elements of the numpy array are not the same as the datatype passed to the array.
Example
import numpy as np
array= [1, 2, 4, [5, [6, 7]]]
np.array(array, dtype=int)
print("the int array is :",array)
The output error that is generated is:
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (4,) + inhomogeneous part.
How to Prevent ValueError : setting an array element with a sequence?
Use a object data type
Since the error occurs due to use of different datatypes in the numpy array elements, we can set the numpy array data type to object, it is a common data type that accepts all elements.
The code becomes :
import numpy as np
array= [1, 2, 4, [5, [6, 7]]]
np.array(array, dtype=object)
print("the int array is :",array)
The output of this code is :
the int array is : [1, 2, 4, [5, [6, 7]]]
Set the datatype and check
You can set the datatype, store it in a variable and then check the array elements, if they are not the same datatype, ignore, else print.
# setting an array element with a sequence
import numpy
array1 = ["go", "linuxCloud"]
Data_type = str
array2 = numpy.array(array1, dtype=Data_type)
Variable = ["go", 1]
if array2.dtype == type(Variable):
array2[1] = Variable
else:
print("not same")
print(array2)
The output of this code is :
not same
['go' 'linuxCloud']
Conclusion
In this article we learned about the fix of the error setting an array element with a sequence. How it is generated and how this error can be avoided or fixed.
Further Reading
Numpy
AttributeError: module 'numpy' has no attribute 'loads'
ValueError: setting an array element with a sequence