Python 如何将meshgrid的输出转换为对应的点数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12864445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:02:20  来源:igfitidea点击:

How to convert the output of meshgrid to the corresponding array of points?

pythonnumpy

提问by juniper-

I want to create a list of points that would correspond to a grid. So if I want to create a grid of the region from (0, 0)to (1, 1), it would contain the points (0, 0), (0, 1), (1, 0)and (1, 0).

我想创建一个与网格相对应的点列表。所以,如果我想从创建区域的网格(0, 0)(1, 1),它将包含点(0, 0)(0, 1)(1, 0)(1, 0)

I know that that this can be done with the following code:

我知道这可以通过以下代码完成:

g = np.meshgrid([0,1],[0,1])
np.append(g[0].reshape(-1,1),g[1].reshape(-1,1),axis=1)

Yielding the result:

产生结果:

array([[0, 0],
       [1, 0],
       [0, 1],
       [1, 1]])

My question is twofold:

我的问题是双重的:

  1. Is there a better way of doing this?
  2. Is there a way of generalizing this to higher dimensions?
  1. 有没有更好的方法来做到这一点?
  2. 有没有办法将其推广到更高维度?

采纳答案by juniper-

I just noticed that the documentation in numpy provides an even faster way to do this:

我刚刚注意到 numpy 中的文档提供了一种更快的方法来做到这一点:

X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([X.ravel(), Y.ravel()])

This can easily be generalized to more dimensions using the linked meshgrid2 function and mapping 'ravel' to the resulting grid.

使用链接的 meshgrid2 函数并将“ravel”映射到生成的网格,可以轻松地将其推广到更多维度。

g = meshgrid2(x, y, z)
positions = np.vstack(map(np.ravel, g))

The result is about 35 times faster than the zip method for a 3D array with 1000 ticks on each axis.

对于每个轴上有 1000 个刻度的 3D 数组,结果比 zip 方法快约 35 倍。

Source: http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html#scipy.stats.gaussian_kde

资料来源:http: //docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html#scipy.stats.gaussian_kde

To compare the two methods consider the following sections of code:

要比较这两种方法,请考虑以下代码段:

Create the proverbial tick marks that will help to create the grid.

创建众所周知的刻度线,这将有助于创建网格。

In [23]: import numpy as np

In [34]: from numpy import asarray

In [35]: x = np.random.rand(100,1)

In [36]: y = np.random.rand(100,1)

In [37]: z = np.random.rand(100,1)

Define the function that mgilson linked to for the meshgrid:

定义 mgilson 链接到网格的函数:

In [38]: def meshgrid2(*arrs):
   ....:     arrs = tuple(reversed(arrs))
   ....:     lens = map(len, arrs)
   ....:     dim = len(arrs)
   ....:     sz = 1
   ....:     for s in lens:
   ....:        sz *= s
   ....:     ans = []
   ....:     for i, arr in enumerate(arrs):
   ....:         slc = [1]*dim
   ....:         slc[i] = lens[i]
   ....:         arr2 = asarray(arr).reshape(slc)
   ....:         for j, sz in enumerate(lens):
   ....:             if j != i:
   ....:                 arr2 = arr2.repeat(sz, axis=j)
   ....:         ans.append(arr2)
   ....:     return tuple(ans)

Create the grid and time the two functions.

创建网格和计时这两个函数。

In [39]: g = meshgrid2(x, y, z)

In [40]: %timeit pos = np.vstack(map(np.ravel, g)).T
100 loops, best of 3: 7.26 ms per loop

In [41]: %timeit zip(*(x.flat for x in g))
1 loops, best of 3: 264 ms per loop

回答by mgilson

Are your gridpoints always integral? If so, you could use numpy.ndindex

你的网格点总是完整的吗?如果是这样,你可以使用numpy.ndindex

print list(np.ndindex(2,2))

Higher dimensions:

更高维度:

print list(np.ndindex(2,2,2))


Unfortunately, this does not meet the requirements of the OP since the integral assumption (starting with 0) is not met. I'll leave this answer only in case someone else is looking for the same thing where those assumptions are true.

不幸的是,这不符合 OP 的要求,因为不满足积分假设(从 0 开始)。我只会留下这个答案,以防其他人在这些假设成立的情况下寻找相同的东西。



Another way to do this relies on zip:

另一种方法依赖于zip

g = np.meshgrid([0,1],[0,1])
zip(*(x.flat for x in g))

This portion scales nicely to arbitrary dimensions. Unfortunately, np.meshgriddoesn't scale well to multiple dimensions, so that part will need to be worked out, or (assuming it works), you could use this SO answerto create your own ndmeshgrid function.

这部分可以很好地缩放到任意维度。不幸的是,np.meshgrid不能很好地扩展到多个维度,因此需要计算出该部分,或者(假设它有效),您可以使用此SO 答案来创建您自己的 ndmeshgrid 函数。

回答by claudiodsf

Yet another way to do it is:

另一种方法是:

np.indices((2,2)).T.reshape(-1,2)

Which can be generalized to higher dimensions, e.g.:

可以推广到更高的维度,例如:

In [60]: np.indices((2,2,2)).T.reshape(-1,3)
Out[60]:
array([[0, 0, 0],
       [1, 0, 0],
       [0, 1, 0],
       [1, 1, 0],
       [0, 0, 1],
       [1, 0, 1],
       [0, 1, 1],
       [1, 1, 1]])