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

Одна ошибка, с которой вы можете столкнуться при использовании 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]) Теперь предположим, что мы пы
  • Редакция Кодкампа

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: операнды не могли транслироваться вместе с фигурами

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.

In this Python tutorial, we will be discussing the concept of setting an array element with a sequence, and also we will see how to fix error, Valueerror: Setting an array element with a sequence:

  • An array of a Different dimension
  • Setting an array Element with a sequence Pandas
  • Valueerror Setting An Array Element with a Sequence in Sklearn
  • Valueerror Setting An Array Element with a Sequence in Tensorflow
  • Valueerror Setting An Array Element with a Sequence in np.vectorize
  • Setting An Array Element with a Sequence in binary text classification

What is ValueError?

ValueError is raised when a function passes an argument of the correct type but an unknown value. Also, the situation should not be prevented by a more precise exception such as Index Error.

  • In Python, the error as ValueError: Setting an array element with a sequence is when we are working with numpy library mostly. This error usually occurs when you are trying to create an array with a list that is not proper multi-dimensional in shape.

valueerror setting an array element with a sequence python

An array of a Different dimension

  • In this example, we will create a numpy array from the list with elements of a different dimension which will throw an error as a value error setting an array element with a sequence
  • Let us see and discuss this error and its solution

Here is the code of an array of a different dimension

import numpy as np

print(np.array([[4, 5,9], [ 7, 9]],dtype = int))

Explanation

  • First we will import the numpy library.
  • Then, we will create the array of two different dimension by using function np.array.
  • Here is the Screenshot of the following given code
Valueerror: Setting an array element with a sequence
Value error array of a different dimension

You can easily see the value error in the display. This is because the structure of the numpy array is not correct.

Solution

In this solution, we will declare the size and length of both the arrays equal and fix the value error.

import numpy as np

print(np.array([[4, 5,9], [ 4,7, 9]],dtype = int))

Here is the Screenshot of the following given code

Valueerror: Setting an array element with a sequence in Python
valueerror setting an array element with a sequence python

This is how to fix value error by setting an array element with a sequence python.

Setting an array Element with a sequence Pandas

In this example, we will import the Python pandas module. Then we will create a variable and use the library pandas dataframe to assign the values. Now, we will print the input, Then it will update the value in the list and got a value error.

Here is the code of value error from pandas

import pandas as pd
out = pd.DataFrame(data = [[600.0]], columns=['Sold Count'], index=['Assignment'])
print (out.loc['Assignment', 'Sold Count'])
 
out.loc['Assignment', 'Sold Count'] = [200.0]
print (out.loc['Assignment', 'Sold Count'])

Explanation

The basic issue is that I would like to set a row and a column in the dataframe to a list .loc method is used and getting a value error

Here is the Screenshot of the following given code

Python Valueerror: Setting an array element with a sequence
Python Setting an array element with a sequence pandas

Solution

In this solution, if you want to solve this error, You will create a non-numeric dtype as an object since it only stores numeric values.

Here is the Code

import pandas as pd
out = pd.DataFrame(data = [[600.0]], columns=['Sold Count'], index=['Assignment'])
print (out.loc['Assignment', 'Sold Count'])
 
out['Sold Count'] = out['Sold Count'].astype(object)
out.loc['Assignment','Sold Count'] = [1000.0,600.0]
print(out)

Here is the Screenshot of the following given code

valueerror: setting an array element with a sequence pandas
valueerror: setting an array element with a sequence pandas

This is how to fix the error, value error: setting an array element with sequence pandas.

Read Python Pandas Drop Rows Example

ValueError Setting An Array Element with a Sequence in Sklearn

  • In this method, we will discuss an error with an iterable sequence in sklearn.
  • Scikit-learn is a free machine learning module for Python. It features various algorithms like SVM, random forests, and k-neighbors, and it also generates Python numerical and scientific libraries like NumPy and SciPy.
  • In machine learning models sometimes numpy array got a value error in the code.
  • In this method, we can easily use the function SVC() and import the sklearn library.

Here is the code of value error setting an array element with a sequence

import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X = np.array([[-3, 4], [5, 7], [1, -1], [3]])
y = np.array([4, 5, 6, 7])
clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
clf.fit(X, y)

Explanation

  • In the above code, we will import a numpy library and sklearn. Now we will create an array X and y. The end element in the numpy array X is of length 1 whereas the other value has length2.
  • This will display the result of a value error for an array element with the Sequence.

Here is the Screenshot of the following given code

valueerror: setting an array element with a sequence sklearn
value error: setting an array element with a sequence sklearn

Solution

  • In this solution, we will change the size of the end element in a given array.
  • we will give all the elements the same length.

Here is the code

import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X = np.array([[-3, 4], [5, 7], [1, -1], [3,2]])
y = np.array([4, 5, 6, 7])
clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
clf.fit(X, y)

Here is the Screenshot of the following given code

valueerror: setting an array element with a sequence sklearn
Solution of an array element with a sequence in Sklearn

This is how to fix the error, valueerror setting an array element with a sequence sklearn.

Read Remove character from string Python

Valueerror Setting An Array Element with a Sequence in Tensorflow

  • In this method, we will learn and discuss an error with a sequence in Tensorflow.
  • A Tensor’s shape is the rank of the Tensor module and the length of each dimension may not always be fully known. In tf.function the shape will only be partially known.
  • In this method, if the shape of every element in a given numpy array is not equal to size you got an error message.

Here is the code of value error array element with a sequence in Tensorflow.

import tensorflow as tf
import numpy as np
 

x = tf.constant([4,5,6,[4,1]])
y = tf.constant([9,8,7,6])
 

res = tf.multiply(x,y)
tf.print(res)

Explanation

In this example, we will import a TensorFlow module then create a numpy array and assign values with different sizes of lengths. Now we create a variable and use the function tf. multiply.

Here is the Screenshot of the following given code

Value error array of different sequence with tensorflow
Value error array of different sequences with TensorFlow

Solution

  • In this solution, we will display and change the length of the end element in a given array.
  • we will give all the values the same length and all the values are of equal shape.

Here is the Code

import tensorflow as tf
import numpy as np
 

x = tf.constant([4,5,6,4])
y = tf.constant([9,8,7,6])
 

res = tf.multiply(x,y)
tf.print(res)

Here is the Screenshot of the following given code

valueerror: setting an array element with a sequence tensorflow
Solution of an array element with a sequence in Tensorflow

This is how to fix the error value error by setting an array element with a sequence TensorFlow.

valueerror setting an array element with a sequence np.vectorize

  • In this method, we will learn and discuss an error with a sequence in np.vectorize
  • The main purpose of np.vectorize is to transform functions that are not numpy aware into functions that can provide and operate on (and return) numpy arrays.
  • In this example, the given function has been vectorized so that for every value in input array t, a numpy array is an output.

Here is the Code of the array element with a sequence in np.vectorize.

import numpy as np

def Ham(t):
    d=np.array([[np.cos(t),np.sqrt(t)],[0,1]],dtype=np.complex128)
    return d
print(Ham)

Explanation

In the above code, this error happens when there are more precise and conflicts with NumPy and python. If the dtype is not given the error may display.

Here is the Screenshot of the following given code

Valueerror array different squence with vectorize
Valueerror array different sequence with vectorize

Solution

  • In this method, the problem is that np.cos(t) and np.sqrt() compute the numpy arrays with the length of t, whereas the second row ([0,1]) maintains the same size.
  • To use np.vectorize with your function, you have to declare the output type.
  • In this method, we can easily use hamvec as a method.

Here is the Code

import numpy as np
def Ham(t):
    d=np.array([[np.cos(t),np.sqrt(t)],[0,1]],dtype=np.complex128)
    return d

HamVec = np.vectorize(Ham, otypes=[np.ndarray])
x=np.array([1,2,3])
y=HamVec(x)
print(y)

Here is the Screenshot of the following given code

valueerror setting an array element with a sequence np.vectorize
Solution of an array element with a sequence in np.vectorize

This is how to fix the error, value error setting an array element with a sequence np.vectorize.

Valueerror Setting An Array Element with a Sequence in binary text classification with tfidfvectorizer

  • In this section, we will learn and discuss an error with a sequence in binary text classification with a tfidfvectorizer.
  • TF-IDF stands for Term Frequency Inverse Document Frequency. This method is a numerical statistic that measures the importance of the word in a document.
  • A Scikit-Learn provides the result of the TfidfVectorizer.
  • I am using pandas and scikit-learn to do binary text classification using text features encoded using TfidfVectorizer on a DataFrame.

Here is the code of binary text classification with tfidfvectorizer

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfVectorizer
data_dict = {'tid': [0,1,2,3,4,5,6,7,8,9],
         'text':['This is the first.', 'This is the second.', 'This is the third.', 'This is the fourth.', 'This is the fourth.', 'This is the fourth.', 'This is the nintieth.', 'This is the fourth.', 'This is the fourth.', 'This is the first.'],
         'cat':[0,0,1,1,1,1,1,0,0,0]}
df = pd.DataFrame(data_dict)
tfidf = TfidfVectorizer(analyzer='word')
df['text'] = tfidf.fit_transform(df['text'])
X_train, X_test, y_train, y_test = train_test_split(df[['tid', 'text']], df[['cat']])
clf = LinearSVC()
clf.fit(X_train, y_train)

Here is the Screenshot of the following given code

Valueerror Setting An Array Element with a Sequence in binary text classification
Value error Setting An Array Element with a Sequence in binary text classification

Solution

  • Tfidfvectorizer returns a 2-Dimension array. You can’t set the column df[‘text’] to a matrix without up the dimensions.
  • Try using only the training data in the fitness routine, and try expanding out the data and set to have more values.

Here is the code

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfVectorizer
data_dict = {'tid': [0,1,2,3,4,5,6,7,8,9],
         'text':['This is the first.', 'This is the second.', 'This is the third.', 'This is the fourth.', 'This is the fourth.', 'This is the fourth.', 'This is the nintieth.', 'This is the fourth.', 'This is the fourth.', 'This is the first.'],
         'cat':[0,0,1,1,1,1,1,0,0,0]}
df = pd.DataFrame(data_dict)
tfidf = TfidfVectorizer(analyzer='word')
df_text = pd.DataFrame(tfidf.fit_transform(df['text']).toarray()) 
X_train, X_test, y_train, y_test = train_test_split(pd.concat([df[['tid']],df_text],axis=1), df[['cat']])
clf = LinearSVC()
clf.fit(X_train, y_train)

Here is the Screenshot of the following given code

valueerror setting an array element with a sequence python
Solution of the array element with a sequence in binary text classification

This is how to fix the error, Valueerror Setting An Array Element with a Sequence in binary text classification with tfidfvectorizer.

You may like the following Python tutorials:

  • Groupby in Python Pandas
  • How to use Pandas drop() function in Python
  • Python NumPy Average with Examples
  • Python NumPy absolute value
  • Check if a list exists in another list Python

In this tutorial, we learned how to fix the error, value error setting an array element with a sequence python.

  • An array of a Different dimension
  • valueerror setting an array element with a sequence python
  • Setting an array Element with a sequence Pandas
  • ValueError Setting An Array Element with a Sequence in Sklearn
  • Valueerror Setting An Array Element with a Sequence in Tensorflow
  • Valueerror Setting An Array Element with a Sequence in np.vectorize
  • Setting An Array Element with a Sequence in binary text classification

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

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.

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.

If you try to put a sequence of more than one element in the place of an array element, you will raise the error: ValueError: setting an array element with a sequence.

To solve this error, ensure that each element in the array is of consistent length and that you do not have a sequence in place of a single element.

The error can also happen if you attempt to create a numpy array with elements of different data-type than that specified with the dtype parameter. To solve this error, you can set the dtype of the numpy array to object.

This tutorial will go through the error in detail and how to solve it with the help of code examples.


Table of contents

  • What is a ValueError?
  • Example #1: Setting An Array Element With A Sequence in Numpy
    • Solution #1: Changing dtype to object
    • Solution #2: Fixing List Structure
  • Example #2: Setting An Array Element With A Sequence in Numpy
    • Solution
  • Example #3: Setting An Array Element With A Sequence in Scikit-Learn
    • Solution
  • Summary

What is a ValueError?

In Python, a value is the information stored within a particular object. You will encounter a ValueError in Python when you use a built-in operation or function that receives an argument with the right type but an inappropriate value.

Example #1: Setting An Array Element With A Sequence in Numpy

Let’s look at an example where we create a numpy array using a list of values. We can select the data type of the numpy array using the dtype parameter. In this example, we will set the data type to an integer. Let’s look at the code:

import numpy as np

arr = [2, 4, 5, [10, [12, 14]]]

data_type=int

np_arr = np.array(arr, dtype=data_type)

print(np_arr)

Let’s run the code to see the result:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
      5 data_type=int
      6
  ---≻7 np_arr = np.array(arr, dtype=data_type)
      8 
      9 print(np_arr)

ValueError: setting an array element with a sequence.

The first error is a TypeError, which we throw because the int() method expects certain data types, but it received a list. The cause of the TypeError is the ValueError. The ValueError occurs because NumPy interprets [10, [12, 14]] as a list, but the data type of the numpy array to create is int. The array can only accept integers as elements.

Solution #1: Changing dtype to object

To solve this error, we can set the data type to object; the array will then support all data types, including list. Let’s look at the revised code:

import numpy as np

arr = [2, 4, 5, [10, [12, 14]]]

data_type=object

np_arr = np.array(arr, dtype=data_type)

print(np_arr)

Let’s run the code to see the result:

[2 4 5 list([10, [12, 14]])]

We have a NumPy object array, which contains references to numpy.str_ objects. Let’s look at the type of the elements in the array:

for i in np_arr:

    print(type(i))
≺class 'numpy.str_'≻
≺class 'numpy.str_'≻
≺class 'numpy.str_'≻
≺class 'numpy.str_'≻

We can still manipulate the integer elements as integers and the list element as a list

val = np_arr[0]
val_sq = val ** 2
print(val_sq)
4
lst = np_arr[3]
print(lst[0])
10

Solution #2: Fixing List Structure

Another way to resolve this is to fix the structure of the original list. If we define the list as a two-dimensional nested list, where each list has the same length, we can pass it to the np.array() method. Let’s look at the revised code:

import numpy as np

arr = [[2, 4, 5], [10, 12, 14]]

data_type=int

np_arr = np.array(arr, dtype=data_type)

print(np_arr)

Let’s run the code to see the result:

[[ 2  4  5]
 [10 12 14]]

The result is a two-dimensional numpy array, which is we can treat as a matrix. For further reading on matrices, go to the articles:

  • How to Multiply Two Matrices in Python
  • How to Find the Transpose of a Matrix in Python

If the dimensions of the nested list are different, the array creation will fail if the data type is not object.

import numpy as np

arr = [[2, 4], [10, 12, 14]]

data_type=int

np_arr = np.array(arr, dtype=data_type)

print(np_arr)
ValueError: setting an array element with a sequence.

To fix this, we either need to ensure the elements are of consistent length or set the data type of the array to object. The resultant array will contain numpy.str_ objects that each refer to a list:

import numpy as np

arr = [[2, 4], [10, 12, 14]]

data_type=object

np_arr = np.array(arr, dtype=data_type)

print(np_arr)
[list([2, 4]) list([10, 12, 14])]

Example #2: Setting An Array Element With A Sequence in Numpy

Let’s look at an example where we try to assign a sequence to an element of an array that only accepts a specific data type.

import numpy as np

arr = ["Python", "is", "really", "fun", "to", "learn"]

data_type = str

np_arr = np.array(arr, dtype=data_type)

np_arr[1] = ["Python", "is"]

In the above code, we attempt to assign a list of strings to a single element in the numpy array, which has the data type str. Let’s run the code to see what happens:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
----≻ 1 np_arr[1] = ["Python", "is"]

ValueError: setting an array element with a sequence

The error occurs because the array expects a string value, but it receives a list with multiple strings.

Solution

To solve this error, we need to set the data type of the numpy array to object. Let’s look at the revised code.

import numpy as np

arr = ["Python", "is", "really", "fun", "to", "learn"]

data_type = object

np_arr = np.array(arr, dtype=data_type)

np_arr[1] = ["Python", "is"]

Let’s run the code to get the result:

['Python' list(['Python', 'is']) 'really' 'fun' 'to' 'learn']

The updated array now has a list object as the first element, and the rest are string objects.

If we want the numpy array to be one specific data type, we need to use an if statement. The if statement will only assign an element if the object has the same data type as the numpy array. Let’s look at the revised code:

import numpy as np

arr = ["Python", "is", "really", "fun", "to", "learn"]

data_type = str

np_arr = np.array(arr, dtype=data_type)

variable = ["Python", "is"]

if np_arr.dtype == type(variable):

    np_arr[1] = variable

else:

    print(f'Variable value does not match the type of the numpy array {data_type}')

    print('Array:  ', np_arr)

The if statement checks if the object we want to assign to the element has the same data type as the numpy array. If it does, then the assignment happens. Otherwise, we get a print statement telling us there is a mismatch in data types. Let’s run the code to see what happens:

Variable value does not match the type of the numpy array ≺class 'str'≻
Array:   ['Python' 'is' 'really' 'fun' 'to' 'learn']

Example #3: Setting An Array Element With A Sequence in Scikit-Learn

Let’s look at another common source of the ValueError. This example will attempt to create a Scikit-Learn pipeline to fit a classifier with some training data.

import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier

# Training data

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

# Labels

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

# Pipeline

clf = make_pipeline(StandardScaler(), MLPClassifier())

# Fitting

clf.fit(X, y)

Let’s run the code to see what happens:

ValueError: setting an array element with a sequence.

We raise the ValueError because the fourth element in the array is a single value, whereas the other three elements contain two values. Therefore, the array has mismatching dimensions. If you want to manipulate multi-dimensional arrays in Python, the elements must be of consistent length.

Solution

To solve this error, we must ensure all elements have the same length. Let’s look at the revised code:

import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier

# Training data

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

#Labels

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

#Pipeline

clf = make_pipeline(StandardScaler(), MLPClassifier())

# Fitting

clf.fit(X, y)

The fourth element now has two values like the rest of the elements. This code will run without any errors.

Summary

Congratulations on reading to the end of this tutorial! The error ValueError: setting an array element with a sequence occurs when you attempt to set an element to a sequence that contains more than one item. The common sources of the error are

  • Attempting to create an array with a nested list of mixed dimensions
  • Creating an array with a given value but the data-type of the value is not the same as the data-type of the numpy array.

To create a multi-dimensional array, ensure your elements have consistent lengths. Otherwise, if you do not need consistent element lengths, you can set the data type of the numpy array to object.

Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

Понравилась статья? Поделить с друзьями:
  • Setracker2 ошибка сети
  • Setracker sign error
  • Setpoint runtime error
  • Setnamedsecurityinfo failed error code 0x2
  • Setfsb пишет chipset error