Home >Backend Development >Python Tutorial >ValueError: Setting an Array Element with a Sequence: Why Does This Happen in NumPy?
ValueError: Setting an Array Element with a Sequence
Why do the following code samples give the error "ValueError: setting an array element with a sequence?":
np.array([[1, 2], [2, 3, 4]]) np.array([1.2, "abc"], dtype=float)
Possible Reason 1: Jagged Arrays
You may be trying to create a "jagged array", where the number of elements in each sublist varies. NumPy does not support this:
np.array([[1, 2], [2, 3, 4]]) # error
The inner lists must have the same length to form a multidimensional array.
Possible Reason 2: Incompatible Types
You may be providing elements of incompatible types to the array. For example, trying to include a string in an array of floats:
np.array([1.2, "abc"], dtype=float) # error
If necessary, you can use the dtype=object option to create an array that holds arbitrary Python objects:
np.array([1.2, "abc"], dtype=object)
The above is the detailed content of ValueError: Setting an Array Element with a Sequence: Why Does This Happen in NumPy?. For more information, please follow other related articles on the PHP Chinese website!