迭代一个 numpy 数组 [英] Iterating over a numpy array
问题描述
是否有更简洁的替代方法:
for x in xrange(array.shape[0]):对于 xrange(array.shape[1]) 中的 y:do_stuff(x, y)
我想出了这个:
for x, y in itertools.product(map(xrange, array.shape)):do_stuff(x, y)
这节省了一个缩进,但仍然很丑.
我希望看起来像这个伪代码:
for x, y in array.indices:do_stuff(x, y)
这样的东西存在吗?
我认为您正在寻找 ndenumerate.
<预><代码>>>>a =numpy.array([[1,2],[3,4],[5,6]])>>>对于(x,y),numpy.ndenumerate(a)中的值:... 打印 x,y...0 00 11 01 12 02 1关于性能.它比列表理解慢一点.
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范围(X.shape[2])])1 个循环,最好的 3 个:每个循环 376 毫秒%timeit 列表(np.ndenumerate(X))1 个循环,最好的 3 个:每个循环 570 毫秒
如果您担心性能,您可以通过查看 ndenumerate
的实现来进一步优化,它可以做两件事,转换为数组和循环.如果你知道你有一个数组,你可以调用平面迭代器的 .coords
属性.
a = X.flat%timeit list([(a.coords, x) for x in a.flat])1 个循环,最好的 3 个:每个循环 305 毫秒
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 came up with this:
for x, y in itertools.product(map(xrange, array.shape)):
do_stuff(x, y)
Which saves one indentation, but is still pretty ugly.
I'm hoping for something that looks like this pseudocode:
for x, y in array.indices:
do_stuff(x, y)
Does anything like that exist?
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
这篇关于迭代一个 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!