迭代一个numpy数组

Ram*_*hum 127 python numpy

是否有一个不那么冗长的替代方案:

for x in xrange(array.shape[0]):
    for y in xrange(array.shape[1]):
        do_stuff(x, y)
Run Code Online (Sandbox Code Playgroud)

我想出了这个:

for x, y in itertools.product(map(xrange, array.shape)):
    do_stuff(x, y)
Run Code Online (Sandbox Code Playgroud)

这节省了一个缩进,但仍然非常难看.

我希望看起来像这个伪代码的东西:

for x, y in array.indices:
    do_stuff(x, y)
Run Code Online (Sandbox Code Playgroud)

这样的事情存在吗?

Sig*_*gyF 179

我想你正在寻找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
Run Code Online (Sandbox Code Playgroud)

关于表现.它比列表理解慢一点.

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
Run Code Online (Sandbox Code Playgroud)

如果你担心性能,可以通过查看实现来进一步优化ndenumerate,这可以做两件事,转换为数组和循环.如果您知道有数组,则可以调用.coordsflat迭代器的属性.

a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop
Run Code Online (Sandbox Code Playgroud)


sen*_*rle 42

如果您只需要索引,可以尝试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)]
Run Code Online (Sandbox Code Playgroud)


C19*_*C19 14

看到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])
Run Code Online (Sandbox Code Playgroud)

y = 3不会工作,使用y *= 0y += 3反而.

  • 或使用y [...] = 3 (2认同)