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.
import numpy as np arr = np.array([[1,2], [1,2,3]], dtype=int) print(arr)
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!
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)
[[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.
import numpy as np arr = np.array([1, 2, 3]) arr = np.array([4, 5]) print(arr)
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
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.
import numpy as np arr = np.array([1, 2, 3]) arr = np.array() print(arr)
[4 2 3]
Thanks for reading. Happy coding!
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.
- Artificial Intelligence2023.03.14Best AI Tools of 2023 (Save Time & Boost Productivity)