How to Fix: ValueError: setting an array element with a sequence


One error you may encounter when using Python is:

ValueError: setting an array element with a sequence.

This error typically occurs when you attempt to cram several numbers into a single position in a NumPy array.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we have the following NumPy array:

import numpy as np

#create NumPy array
data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

Now suppose we attempt to cram two numbers into the first position of the array:

#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.

The error tells us exactly what we did wrong: We attempted to set one element in the NumPy array with a sequence of values.

In particular, we attempted to cram the values ‘4’ and ‘5’ both into the first position of the NumPy array.

This isn’t possible to do, so we receive an error.

How to Fix the Error

The way to fix this error is to simply assign one value into the first position of the array:

#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])

Notice that we don’t receive any error.

If we actually do want to assign two new values to elements in the array, we need to use the following syntax:

#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])

Notice that the first two values were changed in the array while all of the other values remained the same.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix KeyError in Pandas
How to Fix: ValueError: cannot convert float NaN to integer
How to Fix: ValueError: operands could not be broadcast together with shapes

Leave a Reply

Your email address will not be published.