close

[Solved] numpy array: IndexError: too many indices for array

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error numpy array: IndexError: too many indices for array in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How numpy array: IndexError: too many indices for array Error Occurs?

Today I get the following error numpy array: IndexError: too many indices for array in python.

How To Solve numpy array: IndexError: too many indices for array Error ?

  1. How To Solve numpy array: IndexError: too many indices for array Error ?

    To Solve numpy array: IndexError: too many indices for array Error Numpy ndarrays are meant for all elements to have the same length. In this case, your second array doesn't contain lists of the same length, so it ends up being a 1-D array of lists, as opposed to a “proper” 2-D array.

  2. numpy array: IndexError: too many indices for array

    To Solve numpy array: IndexError: too many indices for array Error Numpy ndarrays are meant for all elements to have the same length. In this case, your second array doesn't contain lists of the same length, so it ends up being a 1-D array of lists, as opposed to a “proper” 2-D array.

Solution 1

Numpy ndarrays are meant for all elements to have the same length. In this case, your second array doesn’t contain lists of the same length, so it ends up being a 1-D array of lists, as opposed to a “proper” 2-D array.

From the Numpy docs on N-dimensional arrays:

An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size.

a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
a.shape # (3,4)
a.ndim # 2

b = np.array([[1,2,3,4], [5,6,7,8], [9,10,11]])
b.shape # (3,)
b.ndim # 1

Solution 2

The first array has shape (3,4) and the second has shape (3,). The second array is missing a second dimension. np.array is unable to use this input to construct a matrix (or array of similarly-lengthed arrays). It is only able to make an array of lists.

>>> a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

>>> print(a)
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

>>> print(type(a))
<class 'numpy.ndarray'>


>>> b = np.array([[1,2,3,4], [5,6,7,8], [9,10,11]])

>>> print(b)
[list([1, 2, 3, 4]) list([5, 6, 7, 8]) list([9, 10, 11])]

>>> print(type(b))
<class 'numpy.ndarray'>

So they are both Numpy arrays, but only the first can be treated as a matrix with two dimensions.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read