Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through Numpy Array elements

Is there a more readable way to code a loop in Python that goes through each element of a Numpy array? I have come up with the following code, but it seems cumbersome & not very readable:

import numpy as np
arr01 = np.random.randint(1,10,(3,3))
for i in range(0,(np.shape(arr01[0])[0]+1)):
    for j in range(0,(np.shape(arr01[1])[0]+1)):
        print (arr01[i,j])

I could make it more explicit such as:

import numpy as np
arr01 = np.random.randint(1,10,(3,3))
rows = np.shape(arr01[0])[0]
cols = np.shape(arr01[1])[0]
for i in range(0, (rows + 1)):
    for j in range(0, (cols + 1)):
        print (arr01[i,j])

However, that still seems a bit more cumbersome, compared to other languages, i.e. an equivalent code in VBA could read (supposing the array had already been populated):

dim i, j as integer
for i = lbound(arr01,1) to ubound(arr01,1)
   for j = lbound(arr01,2) to ubound(arr01,2)
       msgBox arr01(i, j)
   next j
next i
like image 859
Jan Stuller Avatar asked Jul 03 '26 05:07

Jan Stuller


1 Answers

You should use the builtin function nditer, if you don't need to have the indexes values.

for elem in np.nditer(arr01):
    print(elem)

EDIT: If you need indexes (as a tuple for 2D table), then:

for index, elem in np.ndenumerate(arr01):
    print(index, elem)
like image 193
pyOliv Avatar answered Jul 05 '26 18:07

pyOliv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!