How to Fix ValueError: Setting An Array Element

Table of Contents ValueError: setting an array element with a sequence1. Setting an array element with a sequence NumPy2. Setting an array element with a sequence Pandas.3. Setting an array element with a sequence sklearn.4. …

ValueError setting an array element

ValueError: setting an array element with a sequence

The “ValueError: setting an array element with a sequence” occurs in python programming in some of the conditions that do not fulfill.

In this article, we are enlightened on the “ValueError: setting an array element with a sequence” with the reasons and how can we solve them when we are working with different modules and packages in python programming.

We are working on four different modules to experience the same  issue.

  • ValueError: setting an array element with a sequence NumPy.
  • ValueError: setting an array element with a sequence Pandas.
  • ValueError: setting an array element with a sequence sklearn.
  • ValueError: setting an array element with a sequence TensorFlow.

1. Setting an array element with a sequence NumPy

Here is the first example of why ValueError: setting an array element with a sequence occurs when you are using the NumPy library. 

This is the simplest example when you are trying to convert the list into NumPy 2D matrix in the output and get the error.

Example 1:

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

output

ValueError                                Traceback (most recent call last)
<ipython-input-27-ba8add8998ec> in <module>
      1 import numpy as np
----> 2 print(np.array([[1,2,3,4], [5, 6, 7]], dtype = int))

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimension. The detected shape was (2,) + inhomogeneous part.

The error in the above code is because the number of the items in the defined lists is not the same. Two lists are separated by a comma and are stored in square brackets. The first list contains four and the second list contains only three items, and both are not the same numbers that create ValueError: setting an array element with a sequence NumPy. 

Here is the solution of how you can run the above code correctly.

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

Output 

[[1 2 3 4]
 [5 6 7 8]]

Example 2:

Another example where you can face this kind of issue is when you do not declare the right data type

import numpy as np
print(np.array([[1, 2, 3, 4], ['a','b','c','d'], ['w','x','y','z']], dtype=float))

You can get the same error when you enter the two different types of data and call the dtype that is opposite to the data of the array. To solve this issue, use the data type that obeys both or multiple data types such as object data type contains mixed numeric and non-numeric data types.

import numpy as np
print(np.array([[1, 2, 3, 4], ['a','b','c','d'], ['w','x','y','z']], dtype=object))

Output

[[1 2 3 4]
 ['a' 'b' 'c' 'd']
 ['w' 'x' 'y' 'z']]

2. Setting an array element with a sequence Pandas.

The issue is created when you want to store data into list form. Single data does not create an issue but when you are using square brackets of the list, there is a need to add dtype otherwise you will get the ValueError as in the below code.

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

You will get the error

ValueError: setting an array element with a sequence.

To solve this error, you need to define the object data type that allows you to use a mixed data type as it supports both numeric and non-numeric data types.

import pandas as pd
output = pd.DataFrame(data = [800.0], columns=['Sold'], index=['Project'],dtype=object)
output.loc['Project','Sold'] = 1000.0,800.0
print(output)

Output

                  Sold
Project (1000.0, 800.0)

3. Setting an array element with a sequence sklearn.

Sklearn is a python library that supports all supervised and unsupervised learning algorithms. In this example, working on sklearn library to proceed the below code where you will get the error due to lengths of “X” array that the last one is different from the rest of all

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

Output

TypeError                                 Traceback (most recent call last)
TypeError: float() argument must be a string or a number, not 'list'

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

ValueError                                Traceback (most recent call last)
<ipython-input-11-928dcb6aa868> in <module>
      6 y = np.array([4, 5, 6, 7])
      7 clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
----> 8 clf.fit(X, y)


D:\Annaconda\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator)
    614                     array = array.astype(dtype, casting="unsafe", copy=False)
    615                 else:
--> 616                     array = np.asarray(array, order=order, dtype=dtype)
    617             except ComplexWarning as complex_warning:
    618                 raise ValueError("Complex data not supported\n"

ValueError: setting an array element with a sequence.

The above code has the same reason of error that all arrays do not contain the same length. 3 of the array has the same length of 2 items, but the fourth array of the same list contains only 1 item that creates the issue of ValueError: setting an array element with a sequence. To solve the error, we use the same length of all arrays.

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

And get the output 

Text

Description automatically generated

4. Setting an array element with a sequence TensorFlow

TensorFlow is a python library that computes numerical data very fast. In this example

  • Import NumPy and TensorFlow libraries.
  • Define NumPy array with data inside them
  • Defined two lists and both have different sizes of length
  • Perform additional operations.
import tensorflow as tf
import numpy as np
 
# Initialize two arrays
a = tf.constant([1,2,3,[4]])
b = tf.constant([5,6,7])
 
# Multiply
result = tf.add(a, b)
tf.print(result)

The program will halt and get the “ValueError Setting an array element with a sequence TensorFlow “ 

OR

“ValueError: Can’t convert Python sequence with mixed types to Tensor” due to different sizes of length in the input. If you want to perform operations like addition, multiplication, subtraction, etc., it is necessary that all arrays have the same length.

Output

ValueError                                Traceback (most recent call last)
<ipython-input-6-15f862bcd121> in <module>()
      3 
      4 # Initialize two arrays
----> 5 a = tf.constant([1,2,3,[4]])
      6 b = tf.constant([5,6,7])
      7 
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/constant_op.py in convert_to_eager_tensor(value, ctx, dtype)
    104       dtype = dtypes.as_dtype(dtype).as_datatype_enum
    105   ctx.ensure_initialized()
--> 106   return ops.EagerTensor(value, ctx.device_name, dtype)
    107 
    108 

ValueError: Can't convert Python sequence with mixed types to Tensor.

To perform the addition operation, we have set all the arrays with the same length.

import tensorflow as tf
import numpy as np
 
# Initialize two arrays
a = tf.constant([1,2,3])
b = tf.constant([4,5,6])
 
# Multiply
result = tf.add(a, b)
tf.print(result)

you get the output of the addition of two arrays.

[5 7 9]

Conclusion

In this article, we have tried to solve the ValueError: setting an array element with a sequence when we are working in different libraries and modules such as NumPy, sklearn, pandas, TensorFlow. The main reason behind this ValueError is array is the defined list is not the same length and that makes an error when printing them as 2D output or defined the incompatible data type that does not support defined data.

Suggested Read: 500 Internal server error

Leave a Comment