Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

loop through numpy array produces typerror output : only integer scalar arrays can be converted to a scalar index

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading