Iterating over a numpy array

前端 未结 3 1913
清酒与你
清酒与你 2020-11-28 01:47

Is there a less verbose alternative to this:

for x in xrange(array.shape[0]):
    for y in xrange(array.shape[1]):
        do_stuff(x, y)

I

相关标签:
3条回答
  • 2020-11-28 02:21

    I think you're looking for the ndenumerate.

    >>> a =numpy.array([[1,2],[3,4],[5,6]])
    >>> for (x,y), value in numpy.ndenumerate(a):
    ...  print x,y
    ... 
    0 0
    0 1
    1 0
    1 1
    2 0
    2 1
    

    Regarding the performance. It is a bit slower than a list comprehension.

    X = np.zeros((100, 100, 100))
    
    %timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
    1 loop, best of 3: 376 ms per loop
    
    %timeit list(np.ndenumerate(X))
    1 loop, best of 3: 570 ms per loop
    

    If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate, which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords attribute of the flat iterator.

    a = X.flat
    %timeit list([(a.coords, x) for x in a.flat])
    1 loop, best of 3: 305 ms per loop
    
    0 讨论(0)
  • 2020-11-28 02:37

    If you only need the indices, you could try numpy.ndindex:

    >>> a = numpy.arange(9).reshape(3, 3)
    >>> [(x, y) for x, y in numpy.ndindex(a.shape)]
    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
    
    0 讨论(0)
  • 2020-11-28 02:39

    see nditer

    import numpy as np
    Y = np.array([3,4,5,6])
    for y in np.nditer(Y, op_flags=['readwrite']):
        y += 3
    
    Y == np.array([6, 7, 8, 9])
    

    y = 3 would not work, use y *= 0 and y += 3 instead.

    0 讨论(0)
提交回复
热议问题