numpy.mgrid :
>>> # assuming a 3x3 array
>>> np.mgrid[:3, :3].swapaxes(-1, 0)
array([[[0, 0],
[1, 0],
[2, 0]],
[[0, 1],
[1, 1],
[2, 1]],
[[0, 2],
[1, 2],
[2, 2]]])
, :
>>> np.mgrid[:3, :3].swapaxes(2, 0).swapaxes(0, 1)
array([[[0, 0],
[0, 1],
[0, 2]],
[[1, 0],
[1, 1],
[1, 2]],
[[2, 0],
[2, 1],
[2, 2]]])
Given that someone timed the results, I also want to introduce a numba manual that “beats everything”:
import numba as nb
import numpy as np
@nb.njit
def _indexarr(a, b, out):
for i in range(a):
for j in range(b):
out[i, j, 0] = i
out[i, j, 1] = j
return out
def indexarr(a, b):
arr = np.empty([a, b, 2], dtype=int)
return _indexarr(a, b, arr)
Timed:
a, b = 400, 500
indexarr(a, b)
%timeit indexarr(a, b)
%timeit np.mgrid[:a, :b].swapaxes(2, 0).swapaxes(0, 1)
%timeit np.mgrid[:a, :b].transpose(1,2,0)
%timeit create_grid(a, b)
and on a smaller array:
a, b = 4, 5
indexarr(a, b)
%timeit indexarr(a, b)
%timeit np.mgrid[:a, :b].swapaxes(2, 0).swapaxes(0, 1)
%timeit np.mgrid[:a, :b].transpose(1,2,0)
%timeit create_grid(a, b)
As promised, it “beats them all” in terms of performance :-)