遍历一个numpy数组 [英] Iterating over a numpy array
问题描述
有没有那么冗长的替代方法呢?
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)
我想到了这个
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?
推荐答案
我认为您正在寻找关于性能.它比列表理解要慢一些.
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
如果您担心性能,可以通过查看ndenumerate
的实现来进一步优化,该实现可以完成两件事,转换为数组并循环执行.如果知道有数组,则可以调用平面迭代器的.coords
属性.
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屋!