Fastest method to create 2D numpy array whose elements are in range

numpy, range

Solution

Can use `np.indices` or `np.meshgrid` for more advanced indexing:

>>> data=np.indices((512,512)).swapaxes(0,2).swapaxes(0,1)
>>> data.shape
(512, 512, 2)

>>> data[5,0]
array([5, 0])
>>> data[5,25]
array([ 5, 25])

This may look odd because its really made to do something like this:

>>> a=np.ones((3,3))
>>> ind=np.indices((2,1))
>>> a[ind[0],ind[1]]=0
>>> a
array([[ 0.,  1.,  1.],
       [ 0.,  1.,  1.],
       [ 1.,  1.,  1.]])

A `mgrid` example:

np.mgrid[0:512,0:512].swapaxes(0,2).swapaxes(0,1)

A meshgrid example:

>>> a=np.arange(0,512)
>>> x,y=np.meshgrid(a,a)
>>> ind=np.dstack((y,x))
>>> ind.shape
(512, 512, 2)

>>> ind[5,0]
array([5, 0])

All are equivalent ways of doing this; however, `meshgrid` can be used to create non-uniform grids.

If you do not mind switching row/column indices you can drop the final `swapaxes(0,1)`.

Problem

I want to create a 2D numpy array where I want to store the coordinates of the pixels such that numpy array looks like this ``` [(0, 0), (0, 1), (0, 2), ...., (0, 510), (0, 511) (1, 0), (1, 1), (1, 2), ...., (1, 510), (1, 511) .. .. .. (511, 0), (511, 1), (511, 2), ...., (511, 510), (511, 511)] ``` This is a ridiculous question but I couldn't find anything yet.

Original source