简体   繁体   English

numpy数组循环中的索引顺序

[英]Index order in loop with numpy array

Is there an specific order to make several loops in a numpy array in order to be fast?是否有特定的顺序在 numpy 数组中进行多个循环以加快速度? I mean, let be A a numpy array with A = A(i,j,k) .我的意思是,让A成为一个 numpy 数组,其中A = A(i,j,k)

If I have to make loops in which order should I do the for sequence?如果我必须按什么顺序循环,我应该按什么顺序执行 for 序列? Thanks谢谢

Are you looping over all dimensions, or just one?你是在所有维度上循环,还是只有一个?

for aa in A:
   print(aa)

iterates over the 1st dimension迭代第一个维度

eg例如

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.无论嵌套循环的顺序如何,都会非常慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM