Меню

Setting an array element with a sequence python ошибка

Why do the following code samples:

np.array([[1, 2], [2, 3, 4]])
np.array([1.2, "abc"], dtype=float)

…all give the following error?

ValueError: setting an array element with a sequence.

Mateen Ulhaq's user avatar

Mateen Ulhaq

23.1k16 gold badges89 silver badges129 bronze badges

asked Jan 12, 2011 at 21:58

MedicalMath's user avatar

7

Possible reason 1: trying to create a jagged array

You may be creating an array from a list that isn’t shaped like a multi-dimensional array:

numpy.array([[1, 2], [2, 3, 4]])         # wrong!
numpy.array([[1, 2], [2, [3, 4]]])       # wrong!

In these examples, the argument to numpy.array contains sequences of different lengths. Those will yield this error message because the input list is not shaped like a «box» that can be turned into a multidimensional array.

Possible reason 2: providing elements of incompatible types

For example, providing a string as an element in an array of type float:

numpy.array([1.2, "abc"], dtype=float)   # wrong!

If you really want to have a NumPy array containing both strings and floats, you could use the dtype object, which allows the array to hold arbitrary Python objects:

numpy.array([1.2, "abc"], dtype=object)

Mateen Ulhaq's user avatar

Mateen Ulhaq

23.1k16 gold badges89 silver badges129 bronze badges

answered Jan 12, 2011 at 23:51

Sven Marnach's user avatar

Sven MarnachSven Marnach

556k115 gold badges923 silver badges825 bronze badges

0

The Python ValueError:

ValueError: setting an array element with a sequence.

Means exactly what it says, you’re trying to cram a sequence of numbers into a single number slot. It can be thrown under various circumstances.

1. When you pass a python tuple or list to be interpreted as a numpy array element:

import numpy

numpy.array([1,2,3])               #good

numpy.array([1, (2,3)])            #Fail, can't convert a tuple into a numpy 
                                   #array element


numpy.mean([5,(6+7)])              #good

numpy.mean([5,tuple(range(2))])    #Fail, can't convert a tuple into a numpy 
                                   #array element


def foo():
    return 3
numpy.array([2, foo()])            #good


def foo():
    return [3,4]
numpy.array([2, foo()])            #Fail, can't convert a list into a numpy 
                                   #array element

2. By trying to cram a numpy array length > 1 into a numpy array element:

x = np.array([1,2,3])
x[0] = np.array([4])         #good



x = np.array([1,2,3])
x[0] = np.array([4,5])       #Fail, can't convert the numpy array to fit 
                             #into a numpy array element

A numpy array is being created, and numpy doesn’t know how to cram multivalued tuples or arrays into single element slots. It expects whatever you give it to evaluate to a single number, if it doesn’t, Numpy responds that it doesn’t know how to set an array element with a sequence.

answered Nov 25, 2017 at 4:40

Eric Leschinski's user avatar

Eric LeschinskiEric Leschinski

142k95 gold badges407 silver badges332 bronze badges

0

In my case , I got this Error in Tensorflow , Reason was i was trying to feed a array with different length or sequences :

example :

import tensorflow as tf

input_x = tf.placeholder(tf.int32,[None,None])



word_embedding = tf.get_variable('embeddin',shape=[len(vocab_),110],dtype=tf.float32,initializer=tf.random_uniform_initializer(-0.01,0.01))

embedding_look=tf.nn.embedding_lookup(word_embedding,input_x)

with tf.Session() as tt:
    tt.run(tf.global_variables_initializer())

    a,b=tt.run([word_embedding,embedding_look],feed_dict={input_x:example_array})
    print(b)

And if my array is :

example_array = [[1,2,3],[1,2]]

Then i will get error :

ValueError: setting an array element with a sequence.

but if i do padding then :

example_array = [[1,2,3],[1,2,0]]

Now it’s working.

answered Apr 2, 2018 at 19:20

Aaditya Ura's user avatar

Aaditya UraAaditya Ura

11.5k7 gold badges46 silver badges83 bronze badges

0

for those who are having trouble with similar problems in Numpy, a very simple solution would be:

defining dtype=object when defining an array for assigning values to it. for instance:

out = np.empty_like(lil_img, dtype=object)

answered Aug 11, 2018 at 6:41

Adam Liu's user avatar

Adam LiuAdam Liu

1,24813 silver badges17 bronze badges

1

In my case, the problem was another. I was trying convert lists of lists of int to array. The problem was that there was one list with a different length than others. If you want to prove it, you must do:

print([i for i,x in enumerate(list) if len(x) != 560])

In my case, the length reference was 560.

answered Mar 14, 2018 at 17:56

Andrés M. Jiménez's user avatar

In my case, the problem was with a scatterplot of a dataframe X[]:

ax.scatter(X[:,0],X[:,1],c=colors,    
       cmap=CMAP, edgecolor='k', s=40)  #c=y[:,0],

#ValueError: setting an array element with a sequence.
#Fix with .toarray():
colors = 'br'
y = label_binarize(y, classes=['Irrelevant','Relevant'])
ax.scatter(X[:,0].toarray(),X[:,1].toarray(),c=colors,   
       cmap=CMAP, edgecolor='k', s=40)

answered Feb 28, 2019 at 18:54

Max Kleiner's user avatar

Max KleinerMax Kleiner

1,22812 silver badges14 bronze badges

1

When the shape is not regular or the elements have different data types, the dtype argument passed to np.array only can be object.

import numpy as np

# arr1 = np.array([[10, 20.], [30], [40]], dtype=np.float32)  # error
arr2 = np.array([[10, 20.], [30], [40]])  # OK, and the dtype is object
arr3 = np.array([[10, 20.], 'hello'])     # OK, and the dtype is also object

«

answered Jul 2, 2020 at 14:55

xiong cai's user avatar

1

In my case, I had a nested list as the series that I wanted to use as an input.

First check: If

df['nestedList'][0]

outputs a list like [1,2,3], you have a nested list.

Then check if you still get the error when changing to input df['nestedList'][0].

Then your next step is probably to concatenate all nested lists into one unnested list, using

[item for sublist in df['nestedList'] for item in sublist]

This flattening of the nested list is borrowed from How to make a flat list out of list of lists?.

answered Aug 3, 2020 at 18:41

questionto42standswithUkraine's user avatar

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:UserscomputersDownloadshe.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:UserscomputersDownloadshe.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']

Introduction

In python, we have discussed many concepts and conversions. In this tutorial, we will be discussing the concept of setting an array element with a sequence. When we try to access some value with the right type but not the correct value, we encounter this type of error. In this tutorial, we will be discussing the concept of ValueError: setting an array element with a sequence in Python.

What is Value Error?

A ValueError occurs when a built-in operation or function receives an argument with the right type but an invalid value. A value is a piece of information that is stored within a certain object.

In python, we often encounter the error as ValueError: setting an array element with a sequence is when we are working with the numpy library. This error usually occurs when the Numpy array is not in sequence.

What Causes Valueerror: Setting An Array Element With A Sequence?

Python always throws this error when you are trying to create an array with a not properly multi-dimensional list in shape. The second reason for this error is the type of content in the array. For example, define the integer array and inserting the float value in it.

Examples Causing Valueerror: Setting An Array Element With A Sequence

Here, we will be discussing the different types of causes through which this type of error gets generated:

1. Array Of A Different Dimension

Let us take an example, in which we are creating an array from the list with elements of different dimensions. In the code, you can see that you have created an array of two different dimensions, which will throw an error as ValueError: setting an array element with a sequence.

import numpy as np
print(np.array([[1, 2,], [3, 4, 5]],dtype = int))

Output:

Array Of A Different Dimension

Explanation:

  • Firstly, we have imported the numpy library with an alias name as np.
  • Then, we will be making the array of two different dimensions with the data type of integer from the np.array() function.
  • The following code will result in the error as Value Error as we cannot access the different dimensions array.
  • At last, you can see the output as an error.

Solution Of An Array Of A Different Dimension

If we try to make the length of both the arrays equal, then we will not encounter any error. So the code will work fine.

import numpy as np
print(np.array([[1, 2, 5], [3, 4, 5]],dtype = int))

Output:

Solution Of An Array Of A Different Dimension

Explanation:

  • Firstly, we have imported the numpy library with an alias name as np.
  • Then, we will make the different dimension array into the same dimension array to remove the error.
  • At last, we will try to print the output.
  • Hence, you can see the output without any error.

Also, Read | [Solved] IndentationError: Expected An Indented Block Error

2. Different Type Of Elements In An Array

Let us take an example, in which we are creating an array from the list with elements of different data types. In the code, you can see that you have created an array of multiple data types values than the defined data type. If we do this, there will be an error generated as ValueError: setting an array element with a sequence.

import numpy as np
print(np.array([2.1, 2.2, "Ironman"], dtype=float))

Output:

Different Type Of Elements In An Array

Explanation:

  • Firstly, we have imported the numpy library with an alias name as np.
  • Then, we will be making the array of two different data types with the data type as a float from the np.array() function.
  • The array contains two data types, i.e., float and string.
  • The following code will result in the error as Value Error as we cannot write the different data types values as the one data type of array.
  • Hence, you can see the output as Value Error.

Solution Of Different Type Of Elements In An Array

If we try to make the data type unrestricted, we should use dtype = object, which will help you remove the error.

import numpy as np
print(np.array([2.1, 2.2, "Ironman"], dtype=object))

Output:

Solution Of Different Type Of Elements In An Array

Explanation:

  • Firstly, we have imported the numpy library with an alias name as np.
  • Then, if we want to access the different data types values in a single array so, we can set the dtype value as an object which is an unrestricted data type.
  • Hence, you can see the correct output, and the code runs correctly without giving any error.

Also, Read | [Solved] TypeError: String Indices Must be Integers

3. Valueerror Setting An Array Element With A Sequence Pandas

In this example, we will be importing the pandas’ library. Then, we will be taking the input from the pandas dataframe function. After that, we will print the input. Then, we will update the value in the list and try to print we get an error.

import pandas as pd
output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1'])
print (output.loc['Project1', 'Sold Count'])

output.loc['Project1', 'Sold Count'] = [400.0]
print (output.loc['Project1', 'Sold Count'])

Output:

Valueerror Setting An Array Element With A Sequence Pandas

Solution Of Value Error From Pandas

If we dont want any error in the following code we need to make the data type as object.

import pandas as pd
output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1'])
print (output.loc['Project1', 'Sold Count'])

output['Sold Count'] = output['Sold Count'].astype(object)
output.loc['Project1','Sold Count'] = [1000.0,800.0]
print(output)

Output:

ValueError: Setting an Array Element With A Sequence Easily

Also, Read | How to Solve TypeError: ‘int’ object is not Subscriptable

4. ValueError Setting An Array Element With A Sequence in Sklearn

Sklearn is a famous python library that is used to execute machine learning methods on a dataset. From regression to clustering, this module has all methods which are needed.

Using these machine learning models over the 2D arrays can sometimes cause a huge ValueError in the code. If your 2D array is not uniform, i.e., if several elements in all the sub-arrays are not the same, it’ll throw an error.

Example Code –

import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

X = np.array([[-1, 1], [2, -1], [1, -1], [2]])
y = np.array([1, 2, 2, 1])

clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
clf.fit(X, y)

Here, the last element in the X array is of length 1, whereas all other elements are of length 2. This will cause the SVC() to throw an error ValueError – Setting an element with a sequence.

Solution –

The solution to this ValueError in Sklearn would be to make the length of arrays equal. In the following code, we’ve changed all the lengths to 2.

import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

X = np.array([[-1, 1], [2, -1], [1, -1], [2, 1]])
y = np.array([1, 2, 2, 1])

clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
clf.fit(X, y)

Also, Read | Invalid literal for int() with base 10 | Error and Resolution

5. ValueError Setting An Array Element With A Sequence in Tensorflow

In Tensorflow, the input shapes have to be correct to process the data. If the shape of every element in your array is not of equal length, you’ll get a ValueError.

Example Code –

import tensorflow as tf
import numpy as np

# Initialize two arrays
x1 = tf.constant([1,2,3,[4,1]])
x2 = tf.constant([5,6,7,8])

# Multiply
result = tf.multiply(x1, x2)
tf.print(result)

Here the last element of the x1 array has length 2. This causes the tf.multiple() to throw a ValueError.

Solution –

The only solution to fix this is to ensure that all of your array elements are of equal shape. The following example will help you understand it –

import tensorflow as tf
import numpy as np

# Initialize two arrays
x1 = tf.constant([1,2,3,1])
x2 = tf.constant([5,6,7,8])

# Multiply
result = tf.multiply(x1, x2)
tf.print(result)

6. ValueError Setting An Array Element With A Sequence in Keras

Similar error in Keras can be observed when an array with different lengths of elements are passed to regression models. As the input might be a mixture of ints and lists, this error may arise.

Example Code –

model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# Compile the model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model
model.fit(X, y, epochs=150, batch_size=10)

>>> ValueError: setting an array element with a sequence.

Here the array X contains a mixture of integers and lists. Moreover, many elements in this array are not fully filled.

Solution –

The solution to this error would be flattening your array and reshaping it to the desired shape. The following transformation will help you to achieve it. keras.layers.Flatten and pd.Series.tolist() will help you to achieve it.

model = Sequential()

model.add(Flatten(input_shape=(2,2)))

model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# Compile the model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model

X = X.tolist()

model.fit(X, y, epochs=150, batch_size=10)

Also, Read | How to solve Type error: a byte-like object is required not ‘str’

Conclusion

In this tutorial, we have learned about the concept of ValueError: setting an array element with a sequence in Python. We have seen what value Error is? And what is ValueError: setting an array element with a sequence? And what are the causes of Value Error? We have discussed all the ways causing the value Error: setting an array element with a sequence with their solutions. All the examples are explained in detail with the help of examples. You can use any of the functions according to your choice and your requirement in the program.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

FAQs

1. How Does ValueError Save Us From Incorrect Data Processing?

We will understand this with the help of small code snippet:

while True:
    try:
        n = input("Please enter an integer: ")
        n = int(n)
        break
    except ValueError:
        print("No valid integer! Please try again ...")
print("Great, you successfully entered an integer!")

Input:

Firstly, we will pass 10.0 as an integer and then 10 as the input. Let us see what the output comes.

Output:

Solving ValueError: Setting an Array Element With A Sequence Easily

Now you can see in the code. When we try to enter the float value in place of an integer value, it shows me a value error which means you can enter only the integer value in the input. Through this, ValueError saves us from incorrect data processing as we can’t enter the wrong data or input.

2. We don’t declare a data type in python, then why is this error arrises in initializing incorrect datatype?

In python, We don’t have to declare a datatype. But, when the ValueError arises, that means there is an issue with the substance of the article you attempted to allocate the incentive to. This is not to be mistaken for types in Python. Hence, Python ValueError is raised when the capacity gets a contention of the right kind; however, it an unseemly worth it.

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Одна ошибка, с которой вы можете столкнуться при использовании Python:

ValueError : setting an array element with a sequence.

Эта ошибка обычно возникает, когда вы пытаетесь втиснуть несколько чисел в одну позицию в массиве NumPy.

В следующем примере показано, как исправить эту ошибку на практике.

Как воспроизвести ошибку

Предположим, у нас есть следующий массив NumPy:

import numpy as np

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

Теперь предположим, что мы пытаемся втиснуть два числа в первую позицию массива:

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

Ошибка говорит нам, что именно мы сделали неправильно: мы попытались установить один элемент в массиве NumPy с последовательностью значений.

В частности, мы попытались втиснуть значения «4» и «5» в первую позицию массива NumPy.

Это невозможно сделать, поэтому мы получаем ошибку.

Как исправить ошибку

Способ исправить эту ошибку — просто присвоить одно значение первой позиции массива:

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

Обратите внимание, что мы не получаем никаких ошибок.

Если мы действительно хотим присвоить два новых значения элементам массива, нам нужно использовать следующий синтаксис:

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

Обратите внимание, что первые два значения в массиве были изменены, а все остальные значения остались прежними.

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить KeyError в Pandas
Как исправить: ValueError: невозможно преобразовать число с плавающей запятой NaN в целое число
Как исправить: ValueError: операнды не могли транслироваться вместе с фигурами

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

ValueError: setting array element with a sequence because of mismatch in array lengths

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.

For example:

import numpy as np

arr = np.array([[1,2], [1,2,3]], dtype=int)

print(arr)

Output:

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!

Solution

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)

Output:

[[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

Replacing a single element with an array won’t work.

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.

For example:

import numpy as np

arr = np.array([1, 2, 3])

arr[0] = np.array([4, 5])

print(arr)

Output:

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

Solution

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.

For example:

import numpy as np

arr = np.array([1, 2, 3])

arr[0] = np.array([4])

print(arr)

Output:

[4 2 3]

Thanks for reading. Happy coding!

Read Also

Python Tips and Tricks

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.

Recent Posts

In Python, if you are mainly working with numpy and creating a multi-dimensional array, you would have encountered valueerror: setting an array element with a sequence.

A ValueError occurs when a function receives an argument of the correct type, but the value of the type is invalid. In this case, if the Numpy array is not in the sequence, you will get a Value Error. 

If you look at the example, the numpy array is 2-dimensional, but at the later stage, we have mixed with single-dimensional array also, and hence Python detects this as an inhomogeneous shape that means the structure of the array varies, and hence Python throws value error.

#Numpy array of different dimensions

import numpy as np
print(np.array([[[1, 2], [3, 4], [5, 6]], [[1],[2]]], dtype=int))

# Output
Traceback (most recent call last):
  File "c:ProjectsTryoutslistindexerror.py", line 2, in <module>
    print(np.array([[[1, 2], [3, 4], [5, 6]], [[1],[2]]], dtype=int))
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.

Solution – By creating the same dimensional array and having identical array elements in each array will solve the problem as shown below. 

#Numpy array of same dimensions

import numpy as np
print(np.array([[[1, 2], [3, 4], [5, 6]]], dtype=int))

# Output
[[[1 2]
  [3 4]
  [5 6]]]

The other possibility where you get Value Error would be when you try to create an array with different types of elements; for instance, consider the below example where we have an array with float and string mixed, which again throws valueerror: could not convert string to float.

# Mutliple data type and dtype as float 

import numpy as np
print(np.array([55.55, 12.5, "Hello World"], dtype=float))

# Output
Traceback (most recent call last):
  File "c:ProjectsTryoutslistindexerror.py", line 2, in <module>
    print(np.array([55.55, 12.5, "Hello World"], dtype=float))
ValueError: could not convert string to float: 'Hello World'

Solution – The solution of this is straightforward if you need either you declare only floating numbers inside an array or if you want both, then make sure that you change the dtype as an object instead of float as shown below.

# Changing the dtype as object and having multiple data type

import numpy as np
print(np.array([55.55, 12.5, "Hello World"], dtype=object))

# Output
[55.55 12.5 'Hello World']

Check out the below examples for more use cases and best practices while working with numpy arrays.

import numpy

numpy.array([1,2,3])               #good

numpy.array([1, (2,3)])            #Fail, can't convert a tuple into a numpy 
                                   #array element


numpy.mean([5,(6+7)])              #good

numpy.mean([5,tuple(range(2))])    #Fail, can't convert a tuple into a numpy 
                                   #array element


def foo():
    return 3
numpy.array([2, foo()])            #good


def foo():
    return [3,4]
numpy.array([2, foo()])            #Fail, can't convert a list into a numpy 
                                   #array element

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

What is ValueError: setting an array element with a sequence?

While programming in Python, especially Numpy a library in Python, programmers encounter an error called ValueError: setting an array element with a sequence. This error usually occurs when the Numpy array is not in sequence.

ValueError: setting an array element with a sequence

Let us see the details of this error and also its solution:

Code

import numpy as np
np.array([[[1, 2], [3, 4], [5, 6]], [[1], [2,4], [3,6]]], dtype=int)

Output

Traceback (most recent call last):
  File "pyprogram.py", line 2, in <module>
    np.array([[[1, 2], [3, 4], [5, 6]], [[1], [2,4], [3,6]]], dtype=int)
ValueError: setting an array element with a sequence.

Explanation

We can see that when this code is executed, the ValueError is raised. This is because the structure of the array is not correct. This two-dimensional array has individual arrays that have two elements each,

[[[1, 2], [3, 4], [5, 6]], [[1], [2,4], [3,6]]], except [1].     

Correct Code

import numpy as np
np.array([ [[1, 2], [3, 4], [5, 6]], [ [1,3], [2,4], [3,6] ] ], dtype=int)

Explanation

Here, no error is encountered as all the individual sequences or arrays have two elements each. So, Numpy can successfully create an array.

In python, you must be familiar with the NumPy package. And when you are creating multi-dimensional NumPy array then you will mostly get the Valueerror: Setting an Array Element with a Sequence error.

In this tutorial, you will know all the causes that lead to this error and how to solve this error.

What does setting an array element with a sequence mean in Python?

In python Valueerror: Setting an Array Element with a Sequence means you are creating a NumPy array of different types of elements in it. For example, mixing int with float or int or float with string. The other case when you will get this error is when you are creating a multiple-dimensional NumPy array. In addition, you are mixing with different dimensions. You will know how to solve this error in a simple way.

Cause 1: Mixing with different Array dimensions

The first case when you will get Valueerror: Setting an Array Element with a Sequence is creating an array with different dimensions or shapes. For example, if you will create a NumPy array of multi-dimension. One is a 2D array and the other is a 3D array.

import numpy as np
numpy_array = np.array([[1,2],[1,2,3]],dtype=int)
print(numpy_array)

When you will run the code you will get the value error.

Valueerror when creating multi-dimensional array

Value error when creating a multi-dimensional array

Solution

The solution for this error is very simple. Just use the array of the same dimensions in a sequence. Instead of [1,2,3] or [1,2] use [1,2] or [1,2,3] respectively.

import numpy as np
numpy_array = np.array([[1,2],[1,2]],dtype=int)
print(numpy_array)

Output

[[1 2]
 [1 2]]

Cause 2: Elements of different type

The other cause for getting Valueerror is you are using different datatype elements for the NumPy array. For example, mixing string with int or float with int e.t.c.

import numpy as np
numpy_array = np.array([[1,2],["foo","foo"]],dtype=float)
print(numpy_array)

Valueerror when creating array with different type of elements

Valueerror when creating an array with different types of elements

Solution

The solution for this case is also very simple. You should make sure that you should use elements of the same type.

import numpy as np
numpy_array = np.array([[1,2],[3,4]],dtype=int)
print(numpy_array)

Output

[[1 2]
[3 4]]

The other solution for this error is that you should define the type of the NumPy array of the object type. Just write dtype=object.

import numpy as np
numpy_array = np.array([[1,2],["foo","foo"]],dtype=object)
print(numpy_array)

Output

[[1 2]
['foo' 'foo']]

END NOTES

Valueerror: Setting an Array Element with a Sequence error generally comes when you are creating a NumPy array using a different multi-dimensional array and different types of elements of the array. The above is the solutions for both cases.

I hope you have liked this tutorial. If you have any queries then you can contact us for more help.

Source:

Numpy array

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Setconfig application обнаружена ошибка windows xp
  • Set object is not subscriptable ошибка