Bianfable
Bianfable

Reputation: 267

Create Numpy Grid in correct order

I have several arrays with points along my x-, y-,...-axes and want to create a grid with all points in it like this:

x = [1, 2, 3]
y = [20, 40, 60, 80]
result = []
for xi in x:
    for yi in y:
        result.append([xi, yi])
np.array(result)

which gives me

array([[ 1, 20],
       [ 1, 40],
       [ 1, 60],
       [ 1, 80],
       [ 2, 20],
       [ 2, 40],
       [ 2, 60],
       [ 2, 80],
       [ 3, 20],
       [ 3, 40],
       [ 3, 60],
       [ 3, 80]])

To do this with numpy I found the following code in this question:

np.vstack(np.meshgrid(x, y)).reshape(2, -1).T

But this gives the result in the wrong order:

array([[ 1, 20],
       [ 2, 20],
       [ 3, 20],
       [ 1, 40],
       [ 2, 40],
       [ 3, 40],
       [ 1, 60],
       [ 2, 60],
       [ 3, 60],
       [ 1, 80],
       [ 2, 80],
       [ 3, 80]])

It goes through the x-values first, then y-values.

I can get around this by using

np.vstack(reversed(np.meshgrid(y, x))).reshape(2, -1).T

but this does not work any more in 3D, where

np.vstack(np.meshgrid(x, y, z)).reshape(3, -1).T

goes through z-values first, then x-values, then y-values.

How can I get the correct order in all dimensions with numpy?

Upvotes: 2

Views: 1193

Answers (1)

akuiper
akuiper

Reputation: 215107

You can specify the matrix indexing ij in np.meshgrid as the indexing parameter to get the reversed order, by default it's the cartesian indexing order xy:

x = [1, 2, 3]
y = [20, 40, 60, 80]

np.stack(np.meshgrid(x, y, indexing='ij'), axis=-1).reshape(-1, 2)
#array([[ 1, 20],
#       [ 1, 40],
#       [ 1, 60],
#       [ 1, 80],
#       [ 2, 20],
#       [ 2, 40],
#       [ 2, 60],
#       [ 2, 80],
#       [ 3, 20],
#       [ 3, 40],
#       [ 3, 60],
#       [ 3, 80]])

In 3d this could be:

np.stack(np.meshgrid(x, y, z, indexing='ij'), axis=-1).reshape(-1, 3)

Upvotes: 4

Related Questions