Jas*_*ite 3 python numpy indices
我试图获取数组中所有元素的索引列表,所以对于1000 x 1000的数组,我最终得到[[0,0),(0,1),...,(999,999) ]。
我做了一个函数来做到这一点,如下所示:
def indices(alist):
results = []
ele = alist.size
counterx = 0
countery = 0
x = alist.shape[0]
y = alist.shape[1]
while counterx < x:
while countery < y:
results.append((counterx,countery))
countery += 1
counterx += 1
countery = 0
return results
Run Code Online (Sandbox Code Playgroud)
我给它计时后,它似乎很慢,因为它大约需要650毫秒才能运行(在慢速笔记本电脑上可以使用)。因此,考虑到numpy必须比平庸的编码更快地执行此操作,我看了看文档并尝试:
indices = [k for k in numpy.ndindex(q.shape)]
which took about 4.5 SECONDS (wtf?)
indices = [x for x,i in numpy.ndenumerate(q)]
better, but 1.5 seconds!
Run Code Online (Sandbox Code Playgroud)
有更快的方法吗?
谢谢
怎么样np.ndindex
?
np.ndindex(1000,1000)
Run Code Online (Sandbox Code Playgroud)
这将返回一个可迭代的对象:
>>> ix = numpy.ndindex(1000,1000)
>>> next(ix)
(0, 0)
>>> next(ix)
(0, 1)
>>> next(ix)
(0, 2)
Run Code Online (Sandbox Code Playgroud)
通常,如果有数组,则可以通过以下方式构建可迭代的索引:
index_iterable = np.ndindex(*arr.shape)
Run Code Online (Sandbox Code Playgroud)
当然,也总是np.ndenumerate
可以这样实现的:
def ndenumerate(arr):
for ix in np.ndindex(*arr.shape):
yield ix,arr[ix]
Run Code Online (Sandbox Code Playgroud)