Iterating over arbitrary dimension of numpy.array

前端 未结 5 1583
生来不讨喜
生来不讨喜 2020-12-01 08:55

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.a         


        
5条回答
  •  [愿得一人]
    2020-12-01 09:40

    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]
    

    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
    

    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).

    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
    

提交回复
热议问题