Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: How to create a grid-like array?

Tags:

python

numpy

I want to create an array which represent X-Y panel (-50, 50). That is: [[-50, -50], [-49,-50],[-48,-50]....[50,50]], which is at length 101*101.

Clearly, I can generate through a double loop from (-50,50). I'm wondering the prefered way of doing this?

like image 724
cqcn1991 Avatar asked Sep 21 '15 02:09

cqcn1991


People also ask

How do I create a NumPy array of a particular shape?

Create a NumPy array from an object implementing the __dlpack__ protocol. Construct an array from data in a text or binary file. Construct an array by executing a function over each coordinate. Create a new 1-dimensional array from an iterable object.

What is a mesh grid?

meshgrid function is used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian indexing or Matrix indexing. Meshgrid function is somewhat inspired from MATLAB. Consider the above figure with X-axis ranging from -4 to 4 and Y-axis ranging from -5 to 5.


2 Answers

numpy.meshgrid is obviously the clearest way to me (as @benbo has mentioned), you need one more step to ravel or flatten the 2D grid array:

In [131]: import numpy as np
     ...: x=np.linspace(-2, 2, 5)
     ...: y=np.linspace(-2, 2, 5)
     ...: xx,yy=np.meshgrid(x,y)
     ...: coords=np.array((xx.ravel(), yy.ravel())).T

In [132]: coords
Out[132]: 
array([[-2., -2.],
       [-1., -2.],
       [ 0., -2.],
       [ 1., -2.],
       [ 2., -2.],
       [-2., -1.],
       ......
       [ 1.,  2.],
       [ 2.,  2.]])

In [133]:

Or as @John mentioned, shorten your code with np.c_ to skip the transpose:

coords=np.c_[xx.ravel(), yy.ravel()]

To benchmark:

In [156]: %timeit coords=np.array((xx.ravel(), yy.ravel())).T
100000 loops, best of 3: 14.6 µs per loop

In [157]: %timeit coords=np.c_[xx.ravel(), yy.ravel()] #not as efficient as ↑
10000 loops, best of 3: 47.6 µs per loop
like image 92
zhangxaochen Avatar answered Nov 12 '22 05:11

zhangxaochen


How about this:

In [15]: import numpy as np

In [16]: a = np.arange(-3,4)

In [17]: a1 = np.tile(a, (7,1))

In [18]: np.dstack((a1, a1.T)).reshape(-1, 2)

Result:

array([[-3, -3],
       [-2, -3],
       [-1, -3],
       [ 0, -3],
       [ 1, -3],
        ....
       [-1,  3],
       [ 0,  3],
       [ 1,  3],
       [ 2,  3],
       [ 3,  3]])
like image 20
Akavall Avatar answered Nov 12 '22 04:11

Akavall