1

Is there an specific order to make several loops in a numpy array in order to be fast? I mean, let be A a numpy array with A = A(i,j,k).

If I have to make loops in which order should I do the for sequence? Thanks

2
  • 2
    If you're looping over a NumPy array in Python, you've already lost. Commented Nov 11, 2015 at 0:29
  • The trick to being fast in numpy is to loop as little as possible, by using numpy's vectorised operations. If you post some example code people may be able to show you how to do this. Commented Nov 11, 2015 at 0:30

1 Answer 1

1

Are you looping over all dimensions, or just one?

for aa in A:
   print(aa)

iterates over the 1st dimension

e.g.

In [479]: A=np.arange(12).reshape(3,4)
In [480]: A
Out[480]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [481]: for a in A:
   .....:     print(a)
   .....:     
[0 1 2 3]
[4 5 6 7]
[ 8  9 10 11]

You can iterate by index over other dimensions

In [482]: for j in range(4):
   .....:     print(A[:,j])
   .....:     
[0 4 8]
[1 5 9]
[ 2  6 10]

or transpose:

In [483]: for a in A.T:
   .....:     print(a)
   .....:     
[0 4 8]
[1 5 9]
[ 2  6 10]
[ 3  7 11]

There's a minor speed advantage if you iterate over the first dimension, rather than the last. But I stress it is minor.

It best to avoid loops entirely, working with compiled methods that operate on the whole array at once. Iteration is, by comparison, much slower.

for i in range(A.shape[0]):
    for j in range(A.shape[1]):
        for k in range(A.shape[2]):
             A[i,j,k]

will be horribly slow, regardless of the order of nesting the loops.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.