创建一个数组,其中每个元素都存储其索引 [英] Create an array where each element stores its indices
本文介绍了创建一个数组,其中每个元素都存储其索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个二维的numpy数组,其中每个元素都是其索引的元组.
I want to create a 2d numpy array where every element is a tuple of its indices.
示例(4x5):
array([[[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4]],
[[1, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4]],
[[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4]],
[[3, 0],
[3, 1],
[3, 2],
[3, 3],
[3, 4]]])
我将创建具有以下列表理解的python list
:
I would create an python list
with the following list comprehension:
[[(y,x) for x in range(width)] for y in range(height)]
是否有更快的方法(例如使用numpy方法)来实现相同目标?
Is there a faster way to achieve the same, maybe with numpy methods?
推荐答案
这是一个基于初始化的方法-
Here's an initialization based method -
def create_grid(m,n):
out = np.empty((m,n,2),dtype=int) #Improvement suggested by @AndrasDeak
out[...,0] = np.arange(m)[:,None]
out[...,1] = np.arange(n)
return out
样品运行-
In [47]: create_grid(4,5)
Out[47]:
array([[[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4]],
[[1, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4]],
[[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4]],
[[3, 0],
[3, 1],
[3, 2],
[3, 3],
[3, 4]]])
到目前为止对在(4,5)
网格和更大尺寸上发布的所有方法的运行时测试-
Runtime test for all approaches posted thus far on (4,5)
grided and bigger sizes -
In [111]: %timeit np.moveaxis(np.indices((4,5)), 0, -1)
...: %timeit np.mgrid[:4, :5].swapaxes(2, 0).swapaxes(0, 1)
...: %timeit np.mgrid[:4,:5].transpose(1,2,0)
...: %timeit create_grid(4,5)
...:
100000 loops, best of 3: 11.1 µs per loop
100000 loops, best of 3: 17.1 µs per loop
100000 loops, best of 3: 17 µs per loop
100000 loops, best of 3: 2.51 µs per loop
In [113]: %timeit np.moveaxis(np.indices((400,500)), 0, -1)
...: %timeit np.mgrid[:400, :500].swapaxes(2, 0).swapaxes(0, 1)
...: %timeit np.mgrid[:400,:500].transpose(1,2,0)
...: %timeit create_grid(400,500)
...:
1000 loops, best of 3: 351 µs per loop
1000 loops, best of 3: 1.01 ms per loop
1000 loops, best of 3: 1.03 ms per loop
10000 loops, best of 3: 190 µs per loop
这篇关于创建一个数组,其中每个元素都存储其索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文