Say I have the following array a and subset 2×2 matrices from it:
import numpy as np
np.random.seed(0)
a = np.random.randint(9,size=(3,2,2))
for i in range(a.shape[0]):
m = a[i]
print(type(m))
print(m)
<class 'numpy.ndarray'>
[[5 0]
[3 3]]
<class 'numpy.ndarray'>
[[7 3]
[5 2]]
<class 'numpy.ndarray'>
[[4 7]
[6 8]]
Now if I want to loop through each of the matrices I get an error:
for i in range(a.shape[0]):
m = a[i]
for j in range(m):
print(j)
TypeError: only integer scalar arrays can be converted to a scalar index
Why is that ? Can’t really debug this typerror.
>Solution :
You are trying to take the range of the matrix m, which doesn’t exist and thus the error. Instead, you should take the range of its shape[0] as you did in the first line for matrix a.
If you want to loop into each position of each matrix, then
import numpy as np
np.random.seed(0)
a = np.random.randint(9,size=(3,2,2))
for i in range(a.shape[0]):
m = a[i]
print(type(m))
print(m)
for i in range(a.shape[0]):
m = a[i]
print("---")
for x in range(m.shape[0]):
for y in range(m.shape[1]):
print(m[x,y])