遍历numpy.array的任意维度 [英] Iterating over arbitrary dimension of numpy.array

查看:858
本文介绍了遍历numpy.array的任意维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有函数可以在numpy数组的任意维上获取迭代器?

Is there function to get an iterator over an arbitrary dimension of a numpy array?

在第一维上迭代很容易...

Iterating over the first dimension is easy...

In [63]: c = numpy.arange(24).reshape(2,3,4)

In [64]: for r in c :
   ....:     print r
   ....: 
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[[12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]

但是在其他维度上进行迭代比较困难.例如,最后一个维度:

But iterating over other dimensions is harder. For example, the last dimension:

In [73]: for r in c.swapaxes(2,0).swapaxes(1,2) :
   ....:     print r
   ....: 
[[ 0  4  8]
 [12 16 20]]
[[ 1  5  9]
 [13 17 21]]
[[ 2  6 10]
 [14 18 22]]
[[ 3  7 11]
 [15 19 23]]

我正在自己生成一个发生器,但是令我惊讶的是,没有像numpy.ndarray.iterdim(axis = 0)这样的函数可以自动执行此操作.

I'm making a generator to do this myself, but I'm surprised there isn't a function named something like numpy.ndarray.iterdim(axis=0) to do this automatically.

推荐答案

您提出的内容相当快,但是可以通过使用更清晰的形式来提高可读性:

What you propose is quite fast, but the legibility can be improved with the clearer forms:

for i in range(c.shape[-1]):
    print c[:,:,i]

或者更好(更快,更通用,更明确):

or, better (faster, more general and more explicit):

for i in range(c.shape[-1]):
    print c[...,i]

但是,上述第一种方法的运行速度似乎是swapaxes()方法的两倍:

However, the first approach above appears to be about twice as slow as the swapaxes() approach:

python -m timeit -s 'import numpy; c = numpy.arange(24).reshape(2,3,4)' \
    'for r in c.swapaxes(2,0).swapaxes(1,2): u = r'
100000 loops, best of 3: 3.69 usec per loop

python -m timeit -s 'import numpy; c = numpy.arange(24).reshape(2,3,4)' \
    'for i in range(c.shape[-1]): u = c[:,:,i]'
100000 loops, best of 3: 6.08 usec per loop

python -m timeit -s 'import numpy; c = numpy.arange(24).reshape(2,3,4)' \
    'for r in numpy.rollaxis(c, 2): u = r'
100000 loops, best of 3: 6.46 usec per loop

我猜这是因为swapaxes()不复制任何数据,并且因为c[:,:,i]的处理可能是通过通用代码完成的(该代码处理了:被更复杂的切片替换的情况)

I would guess that this is because swapaxes() does not copy any data, and because the handling of c[:,:,i] might be done through general code (that handles the case where : is replaced by a more complicated slice).

但是请注意,更明确的第二个解决方案c[...,i]既清晰又快速:

Note however that the more explicit second solution c[...,i] is both quite legible and quite fast:

python -m timeit -s 'import numpy; c = numpy.arange(24).reshape(2,3,4)' \
    'for i in range(c.shape[-1]): u = c[...,i]'
100000 loops, best of 3: 4.74 usec per loop

这篇关于遍历numpy.array的任意维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆