. Advertisement .
..3..
. Advertisement .
..4..
Hello, everyone! I’m having a trouble with: ”index 2 is out of bounds for axis 0 with size 2”, but I didn’t know how to fix it. Here is the program which I run:
main.py
import numpy as np
arr = np.array([])
print(arr.shape) # (2,)
print(arr.size) # 2
# IndexError: index 2 is out of bounds for axis 0 with size 2
print(arr[2])
I have read a lot of documentaries but I haven’t found the desired answer. Does anyone have suggestions for me? Please write down. Thanks!
The cause:
You have got this error because you attempted to access the first item in an array which is vacant.
Solution:
To solve this problem, you need to check whether the size of array is bigger than 2 before accessing its to the first element or not first.
If the array’s size is bigger than 2, the
if
block will run. In the case the array’s size is not bigger than 2, theelse
block will run.Another way, a
try/except
statement also helps you to solve this error.Or you can utilize the keywords of pass in the block of except. And remember that when you declare a numpy array, you have to ensure that it has the correct size and do not access array item at index of 0.
Finally, make sure that you don’t create an array which has N columns and 0 rows.
If you do as the my above suggestions, your error will disappear. Good lucks!