NumPy: iterate over outer dimension of numpy array using nditer

前端 未结 2 1254
盖世英雄少女心
盖世英雄少女心 2021-01-15 00:57

I am unable to iterate over the outer axis of a numpy array.

import numpy as np

a = np.arange(2*3).reshape(2,3)
it = np.nditer(a)
for i in it:
    print i
<         


        
相关标签:
2条回答
  • 2021-01-15 01:22

    It's easier to control the iteration with a plain for:

    In [17]: a
    Out[17]: 
    array([[0, 1, 2],
           [3, 4, 5]])
    In [18]: for row in a:
        ...:     print(row)
        ...:     
    [0 1 2]
    [3 4 5]
    

    Doing this with nditer is just plain awkward. Unless you need broadcasting use cython as described at the end of the page, nditer does not offer any speed advantages. Even with cython, I've gotten better speeds with memoryviews than with nditer.

    Look at np.ndindex. It creates a dummy array with reduced dimensions, and does a nditer on that:

    In [20]: for i in np.ndindex(a.shape[0]):
        ...:     print(a[i,:])
        ...:     
    [[0 1 2]]
    [[3 4 5]]
    

    Got it:

    In [31]: for x in np.nditer(a.T.copy(), flags=['external_loop'], order='F'):
        ...:     print(x)
    
    [0 1 2]
    [3 4 5]
    

    Like I said - awkward

    I recently explored the difference between direct iteration and nditer over a 1d structured array: https://stackoverflow.com/a/43005985/901925

    0 讨论(0)
  • 2021-01-15 01:39

    You can iterate it over just like you iterate over a 1D array to get the output like you want.

     for k,v in enumerate(a):
          print(v)
    
    0 讨论(0)
提交回复
热议问题