Arrays in Python are one dimensional and two dimensional. Two-dimensional arrays consist of one or more arrays inside it. You can access the elements in a 2D array by mentioning two indices. The first index represents the position of the inner array. The other index represents the element within this inner array.
Python IndexError: too many indices for array
While using a numpy array, you might come across an error IndexError: too many indices for an array. This occurs when you are trying to access the elements of a one-dimensional numpy array as a 2D array. To avoid this error, you need to mention the correct dimensions of the array.
This error is thrown by Python 'numpy array' library when you try to access a single-dimensional array into multiple dimensional arrays.
Example
# Code with error
# Importing the numpy library
import numpy as np
# Declaring and Initializing the one Dimension Array
x = np.array([212,312,2,12,124,142,12])
# Printing the result
print(x[0,3])
OUTPUT:
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(x[0,3])
IndexError: too many indices
In the above example, we have declared a single dimensional array using numpy library array, but later in the code, we are trying to print it as a two-dimensional array.
Solution
To resolve this error, you have re-check the dimensions which you are using and the dimension you are declaring and initializing
# Code without errors
# Importing the numpy library
import numpy as np
# Declaring and initializing the one dimension array
x = np.array([212,312,2,12,124,142,12])
# To check the dimension of the array
print("Shape of the array = ",np.shape(x));
# Printing the result
print(x[0])
OUTPUT:
Shape of the array = (7,)
212
How to check the Dimension of Array
To check the dimension of your declared array use len(x.shape) function of the numpy library.
import numpy as np
myarray = np.array([[[2,4,4],[2,34,9]],[[12,3,4],[2,1,3]],[[2,2,2],[2,1,3]]])
print("Array Dimension = ",len(myarray.shape))
Output
Array Dimension = 3
Conclusion
The indices of the numpy array have to be mentioned according to the size. For a one dimensional array, mention one index. For 2D arrays, specify two indices. The best way to go about it is by using the len(myarray.shape).