How to fix 'ValueError: The requested array has an inhomogeneous shape after 1 dimensions'?

Learn, how can we fix 'ValueError: The requested array has an inhomogeneous shape after 1 dimensions'?
By Pranit Sharma Last updated : December 20, 2023

'ValueError: The requested array has an inhomogeneous shape after 1 dimensions' – How to fix?

Suppose we are working on N-D arrays and we are creating different rows for an N-D array. Many times, we face this ValueError that says that the requested array has an inhomogeneous shape after 1 dimensions.

This type of error occurs because we do not put an equal number of elements in each row. To solve this problem, we must put an equal number of values in all the rows of an ND numpy array.

Let us understand with the help of an example,

Example

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([[1,2,3,4,5],[6,7,8,9]])

# Display original array
print("Original array:\n",arr,"\n")

Output

Example 1: How to fix 'ValueError: The requested array has an inhomogeneous shape after 1 dimensions'?

Python code to fix "The requested array has an inhomogeneous shape after 1 dimensions" Error

To fix this issue, put an equal number of elements in each row and you must specify 'dtype=object' when creating the ndarray.

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([[1,2,3,4,5],[6,7,8,9,10]], dtype="object")

# Display original array
print("Original array:\n",arr,"\n")

Output

Example 2: How to fix 'ValueError: The requested array has an inhomogeneous shape after 1 dimensions'?

In this example, we have used the following Python topics that you should learn:

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.