NumPy中meshgrid的用途是什么?

2cmtqfgy  于 12个月前  发布在  其他
关注(0)|答案(9)|浏览(101)

np.meshgrid的作用是什么?我知道它会为绘图创建某种坐标网格,但我看不到它的直接好处。
官方文档给出了下面的例子,但它的输出对我来说没有意义:

x = np.arange(-5, 5, 1)
y = np.arange(-5, 5, 1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,z)
7vux5j2d

7vux5j2d1#

meshgrid的目的是用x值数组和y值数组创建一个矩形网格。
因此,例如,如果我们想要创建一个网格,其中在x和y方向上的每个0到4之间的整数值处都有一个点。要创建一个矩形网格,我们需要xy点的每个组合。
这将是25分,对吧?因此,如果我们想为所有这些点创建一个x和y数组,我们可以做以下事情。

x[0,0] = 0    y[0,0] = 0
x[0,1] = 1    y[0,1] = 0
x[0,2] = 2    y[0,2] = 0
x[0,3] = 3    y[0,3] = 0
x[0,4] = 4    y[0,4] = 0
x[1,0] = 0    y[1,0] = 1
x[1,1] = 1    y[1,1] = 1
...
x[4,3] = 3    y[4,3] = 4
x[4,4] = 4    y[4,4] = 4

这将导致以下xy矩阵,使得每个矩阵中对应元素的配对给出网格中点的x和y坐标。

x =   0 1 2 3 4        y =   0 0 0 0 0
      0 1 2 3 4              1 1 1 1 1
      0 1 2 3 4              2 2 2 2 2
      0 1 2 3 4              3 3 3 3 3
      0 1 2 3 4              4 4 4 4 4

然后我们可以绘制这些图来验证它们是否是网格:

plt.plot(x,y, marker='.', color='k', linestyle='none')

显然,这变得非常乏味,特别是对于大范围的xy。相反,meshgrid实际上可以为我们生成以下内容:所有我们必须指定的是唯一的xy值。

xvalues = np.array([0, 1, 2, 3, 4]);
yvalues = np.array([0, 1, 2, 3, 4]);

现在,当我们调用meshgrid时,我们会自动获得之前的输出。

xx, yy = np.meshgrid(xvalues, yvalues)

plt.plot(xx, yy, marker='.', color='k', linestyle='none')

创建这些矩形网格对于许多任务都很有用。在你在文章中提供的例子中,它只是一种在xy的值范围内对函数(sin(x**2 + y**2) / (x**2 + y**2))进行采样的方法。
因为这个函数是在矩形网格上采样的,所以这个函数现在可以被可视化为一个“图像”。

此外,结果现在可以传递给期望矩形网格上的数据的函数(即,contourf

ca1c2owp

ca1c2owp2#

使用Microsoft Excel:

atmip9wb

atmip9wb3#

实际上,np.meshgrid的用途已经在文档中提到:
np.meshgrid
从坐标向量返回坐标矩阵。
在给定一维坐标阵列x1,x2,...,xn的情况下,制作N-D坐标阵列,用于N-D网格上的N-D标量/向量场的向量化计算。
所以它的主要目的是创建一个坐标矩阵。
你可能会问自己:

为什么需要创建坐标矩阵?

Python/NumPy需要坐标矩阵的原因是坐标与值之间没有直接关系,除非坐标从零开始并且是纯正整数。然后你可以只使用数组的索引作为索引。然而,当情况并非如此时,您需要以某种方式将坐标与数据一起存储。这就是网格的用武之地。
假设你的数据是:
但是,每个值代表一个3 x 2公里的区域(水平x垂直)。假设你的原点是左上角,你想用数组来表示距离,你可以用途:

import numpy as np
h, v = np.meshgrid(np.arange(3)*3, np.arange(3)*2)

其中V是:

array([[0, 0, 0],
       [2, 2, 2],
       [4, 4, 4]])

和h:

array([[0, 3, 6],
       [0, 3, 6],
       [0, 3, 6]])

所以如果你有两个索引,比如xy(这就是为什么meshgrid的返回值通常是xxxs而不是x的原因,在这个例子中,我选择了h来表示水平!)然后你可以得到点的x坐标,点的y坐标和该点的值,通过使用:

h[x, y]    # horizontal coordinate
v[x, y]    # vertical coordinate
data[x, y]  # value

这使得跟踪坐标变得更加容易(更重要的是),您可以将它们传递给需要知道坐标的函数。

稍微长一点的解释

然而,np.meshgrid本身并不经常被直接使用,大多数情况下,人们只是使用np.mgridnp.ogrid中的一个 * 类似 * 对象。这里np.mgrid代表sparse=Falsenp.ogrid代表sparse=True(我指的是np.meshgridsparse参数)。请注意,np.meshgridnp.ogridnp.mgrid之间存在显著差异:前两个返回值(如果有两个或更多)将被反转。通常这并不重要,但你应该根据上下文给给予有意义的变量名。
例如,在2D网格和matplotlib.pyplot.imshow的情况下,将第一个返回项命名为np.meshgridx和第二个返回项命名为y是有意义的,而对于np.mgridnp.ogrid则相反。

np.ogrid和稀疏网格

>>> import numpy as np
>>> yy, xx = np.ogrid[-5:6, -5:6]
>>> xx
array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5]])
>>> yy
array([[-5],
       [-4],
       [-3],
       [-2],
       [-1],
       [ 0],
       [ 1],
       [ 2],
       [ 3],
       [ 4],
       [ 5]])

如前所述,与np.meshgrid相比,输出是相反的,这就是为什么我将其解包为yy, xx而不是xx, yy

>>> xx, yy = np.meshgrid(np.arange(-5, 6), np.arange(-5, 6), sparse=True)
>>> xx
array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5]])
>>> yy
array([[-5],
       [-4],
       [-3],
       [-2],
       [-1],
       [ 0],
       [ 1],
       [ 2],
       [ 3],
       [ 4],
       [ 5]])

这看起来已经像坐标,特别是2D图的x和y线。
可视化:

yy, xx = np.ogrid[-5:6, -5:6]
plt.figure()
plt.title('ogrid (sparse meshgrid)')
plt.grid()
plt.xticks(xx.ravel())
plt.yticks(yy.ravel())
plt.scatter(xx, np.zeros_like(xx), color="blue", marker="*")
plt.scatter(np.zeros_like(yy), yy, color="red", marker="x")

np.mgrid和密集/充实的网格

>>> yy, xx = np.mgrid[-5:6, -5:6]
>>> xx
array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5]])
>>> yy
array([[-5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5],
       [-4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4],
       [-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3],
       [-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2],
       [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1],
       [ 2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2],
       [ 3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3],
       [ 4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4],
       [ 5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5]])

这同样适用于这里:输出与np.meshgrid相反:

>>> xx, yy = np.meshgrid(np.arange(-5, 6), np.arange(-5, 6))
>>> xx
array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5]])
>>> yy
array([[-5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5],
       [-4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4],
       [-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3],
       [-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2],
       [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1],
       [ 2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2],
       [ 3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3],
       [ 4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4],
       [ 5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5]])

ogrid不同,这些数组包含所有xxyy坐标,坐标在-5 <= xx <= 5;-5 <= yy <= 5网格。

yy, xx = np.mgrid[-5:6, -5:6]
plt.figure()
plt.title('mgrid (dense meshgrid)')
plt.grid()
plt.xticks(xx[0])
plt.yticks(yy[:, 0])
plt.scatter(xx, yy, color="red", marker="x")

功能

它不仅限于2D,这些函数适用于任意维度(好吧,Python中函数的参数数量有最大值,NumPy允许的维度数量也有最大值):

>>> x1, x2, x3, x4 = np.ogrid[:3, 1:4, 2:5, 3:6]
>>> for i, x in enumerate([x1, x2, x3, x4]):
...     print('x{}'.format(i+1))
...     print(repr(x))
x1
array([[[[0]]],

       [[[1]]],

       [[[2]]]])
x2
array([[[[1]],

        [[2]],

        [[3]]]])
x3
array([[[[2],
         [3],
         [4]]]])
x4
array([[[[3, 4, 5]]]])

>>> # equivalent meshgrid output, note how the first two arguments are reversed and the unpacking
>>> x2, x1, x3, x4 = np.meshgrid(np.arange(1,4), np.arange(3), np.arange(2, 5), np.arange(3, 6), sparse=True)
>>> for i, x in enumerate([x1, x2, x3, x4]):
...     print('x{}'.format(i+1))
...     print(repr(x))
# Identical output so it's omitted here.

即使这些也适用于1D,也有两个(更常见的)1D网格创建函数:

除了startstop参数外,它还支持step参数(即使是表示步骤数的复杂步骤):

>>> x1, x2 = np.mgrid[1:10:2, 1:10:4j]
>>> x1  # The dimension with the explicit step width of 2
array([[1., 1., 1., 1.],
       [3., 3., 3., 3.],
       [5., 5., 5., 5.],
       [7., 7., 7., 7.],
       [9., 9., 9., 9.]])
>>> x2  # The dimension with the "number of steps"
array([[ 1.,  4.,  7., 10.],
       [ 1.,  4.,  7., 10.],
       [ 1.,  4.,  7., 10.],
       [ 1.,  4.,  7., 10.],
       [ 1.,  4.,  7., 10.]])

应用

你特别问了它的用途,事实上,如果你需要一个坐标系,这些网格非常有用。
例如,如果你有一个NumPy函数,它可以计算两个维度的距离:

def distance_2d(x_point, y_point, x, y):
    return np.hypot(x-x_point, y-y_point)

你想知道每个点的距离:

>>> ys, xs = np.ogrid[-5:5, -5:5]
>>> distances = distance_2d(1, 2, xs, ys)  # distance to point (1, 2)
>>> distances
array([[9.21954446, 8.60232527, 8.06225775, 7.61577311, 7.28010989,
        7.07106781, 7.        , 7.07106781, 7.28010989, 7.61577311],
       [8.48528137, 7.81024968, 7.21110255, 6.70820393, 6.32455532,
        6.08276253, 6.        , 6.08276253, 6.32455532, 6.70820393],
       [7.81024968, 7.07106781, 6.40312424, 5.83095189, 5.38516481,
        5.09901951, 5.        , 5.09901951, 5.38516481, 5.83095189],
       [7.21110255, 6.40312424, 5.65685425, 5.        , 4.47213595,
        4.12310563, 4.        , 4.12310563, 4.47213595, 5.        ],
       [6.70820393, 5.83095189, 5.        , 4.24264069, 3.60555128,
        3.16227766, 3.        , 3.16227766, 3.60555128, 4.24264069],
       [6.32455532, 5.38516481, 4.47213595, 3.60555128, 2.82842712,
        2.23606798, 2.        , 2.23606798, 2.82842712, 3.60555128],
       [6.08276253, 5.09901951, 4.12310563, 3.16227766, 2.23606798,
        1.41421356, 1.        , 1.41421356, 2.23606798, 3.16227766],
       [6.        , 5.        , 4.        , 3.        , 2.        ,
        1.        , 0.        , 1.        , 2.        , 3.        ],
       [6.08276253, 5.09901951, 4.12310563, 3.16227766, 2.23606798,
        1.41421356, 1.        , 1.41421356, 2.23606798, 3.16227766],
       [6.32455532, 5.38516481, 4.47213595, 3.60555128, 2.82842712,
        2.23606798, 2.        , 2.23606798, 2.82842712, 3.60555128]])

如果在密集网格而不是开放网格中传递,输出将是相同的。NumPys广播使之成为可能!
让我们可视化结果:

plt.figure()
plt.title('distance to point (1, 2)')
plt.imshow(distances, origin='lower', interpolation="none")
plt.xticks(np.arange(xs.shape[1]), xs.ravel())  # need to set the ticks manually
plt.yticks(np.arange(ys.shape[0]), ys.ravel())
plt.colorbar()

这也是NumPys mgridogrid变得非常方便的时候,因为它允许您轻松更改网格的分辨率:

ys, xs = np.ogrid[-5:5:200j, -5:5:200j]
# otherwise same code as above

但是,由于imshow不支持xy输入,因此必须手动更改刻度。如果它能接受xy坐标,那就太方便了,对吧?
使用NumPy编写自然处理网格的函数很容易。此外,NumPy、SciPy、matplotlib中有几个函数希望你传入网格。
我喜欢图像,所以让我们探索matplotlib.pyplot.contour

ys, xs = np.mgrid[-5:5:200j, -5:5:200j]
density = np.sin(ys)-np.cos(xs)
plt.figure()
plt.contour(xs, ys, density)

请注意,坐标已经正确设置!如果你只是传入density,情况就不会是这样了。
或者给予另一个有趣的例子,使用astropy models(这次我不太关心坐标,我只是用它们来创建 * 一些 * 网格):

from astropy.modeling import models
z = np.zeros((100, 100))
y, x = np.mgrid[0:100, 0:100]
for _ in range(10):
    g2d = models.Gaussian2D(amplitude=100, 
                           x_mean=np.random.randint(0, 100), 
                           y_mean=np.random.randint(0, 100), 
                           x_stddev=3, 
                           y_stddev=3)
    z += g2d(x, y)
    a2d = models.AiryDisk2D(amplitude=70, 
                            x_0=np.random.randint(0, 100), 
                            y_0=np.random.randint(0, 100), 
                            radius=5)
    z += a2d(x, y)

虽然这只是“为了外观”,但Scipy中与功能模型和拟合相关的几个函数(例如scipy.interpolate.interp2dscipy.interpolate.griddata甚至显示了使用np.mgrid的示例)等。需要网格。大多数这些工作与开放的网格和密集的网格,但有些只与其中之一。

zyfwsgd6

zyfwsgd64#

假设你有一个函数:

def sinus2d(x, y):
    return np.sin(x) + np.sin(y)

比如,你想看看它在0到2* π的范围内是什么样子的。你会怎么做?np.meshgrid进来了:

xx, yy = np.meshgrid(np.linspace(0,2*np.pi,100), np.linspace(0,2*np.pi,100))
z = sinus2d(xx, yy) # Create the image on this grid

这样的图看起来像这样:

import matplotlib.pyplot as plt
plt.imshow(z, origin='lower', interpolation='none')
plt.show()

所以np.meshgrid只是一种方便。原则上,可以通过以下方式实现同样的目标:

z2 = sinus2d(np.linspace(0,2*np.pi,100)[:,None], np.linspace(0,2*np.pi,100)[None,:])

但是在那里你需要意识到你的维度(假设你有两个以上的维度...)和正确的广播。np.meshgrid为您做了所有这些。
此外,meshgrid允许您删除坐标和数据,例如,如果您想要进行插值但排除某些值:

condition = z>0.6
z_new = z[condition] # This will make your array 1D

那么你现在怎么做插值呢你可以给予xy插值函数,比如scipy.interpolate.interp2d,所以你需要一种方法来知道哪些坐标被删除了:

x_new = xx[condition]
y_new = yy[condition]

然后你仍然可以使用“正确”的坐标进行插值(尝试不使用meshgrid,你会有很多额外的代码):

from scipy.interpolate import interp2d
interpolated = interp2d(x_new, y_new, z_new)

原始的meshgrid允许你再次在原始网格上得到插值:

interpolated_grid = interpolated(xx[0], yy[:, 0]).reshape(xx.shape)

这些只是我使用meshgrid的一些例子,可能还有更多。

iklwldmw

iklwldmw5#

简短回答

meshgrid的目的是通过NumPy库中提供的更快的矢量化操作来帮助replace slow Python loopsmeshgrid的作用是准备向量化操作所需的2D数组。

基本原理示例

假设我们有两个值序列,

a = [2,7,9,20]    
b = [1,6,7,9]    ​

我们想对每一对可能的值执行一个操作,一个取自第一个列表,一个取自第二个列表。我们还想存储结果。例如,假设我们想要获得每个可能对的值的总和。

  • 缓慢而费力的方法 *
c = []    
for i in range(len(b)):    
    row = []    
    for j in range(len(a)):    
        row.append (a[j] + b[i])
    c.append (row)    
print (c)

测试结果:

[[3, 8, 10, 21],
 [8, 13, 15, 26],
 [9, 14, 16, 27],
 [11, 16, 18, 29]]
  • 快速简便的方法 *
i,j = np.meshgrid (a,b)    
c = i + j    
print (c)

测试结果:

[[ 3  8 10 21]
 [ 8 13 15 26]
 [ 9 14 16 27]
 [11 16 18 29]]

从这个基本的例子中,你可以看到显式的慢Python循环是如何被Numpy库中隐藏的更快的C循环所取代的。这一原理广泛用于3D操作,包括彩色像素图。常见的例子是3D绘图。

常用用途:3D绘图

x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

(取自本网站)
meshgrid用于创建在-4和+4之间的坐标对,在X和Y方向上每个增量为0.25。每一对都用来从中找到R和Z。这种准备坐标“网格”的方法经常用于绘制3D表面或着色2D表面。

引擎盖下的网格

meshgrid准备的两个阵列是:

(array([[ 2,  7,  9, 20],
        [ 2,  7,  9, 20],
        [ 2,  7,  9, 20],
        [ 2,  7,  9, 20]]),

 array([[1, 1, 1, 1],
        [6, 6, 6, 6],
        [7, 7, 7, 7],
        [9, 9, 9, 9]]))

这些数组是通过水平或垂直重复提供的值创建的。这两个数组对于向量运算是形状兼容的。

来源

numpy.meshgridfrom MATLAB,就像许多其他NumPy函数一样。因此,您也可以研究MATLAB中的示例,以了解meshgrid的使用情况,3D绘图的代码看起来像the same in MATLAB

1hdlvixo

1hdlvixo6#

meshgrid有助于从两个一维数组中创建一个矩形网格,其中包含两个数组中的所有点对。

x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 2, 3, 4])

现在,如果你已经定义了一个函数f(x,y),你想把这个函数应用到数组'x'和'y'中所有可能的点的组合,那么你可以这样做:

f(*np.meshgrid(x, y))

比如说,如果你的函数只产生两个元素的乘积,那么这就是如何实现一个carnival乘积,对于大型数组来说是有效的。
引用自here

lmvvr0a8

lmvvr0a87#

基本思路

给定可能的x值xs(将它们视为图的x轴上的刻度线)和可能的y值,ysmeshgrid生成相应的(x,y)网格点集-类似于set((x, y) for x in xs for y in yx)。例如,如果xs=[1,2,3]ys=[4,5,6],我们将得到坐标{(1,4), (2,4), (3,4), (1,5), (2,5), (3,5), (1,6), (2,6), (3,6)}

返回值形式

但是,meshgrid返回的表示与上面的表达式有两个不同之处:

  • 首先 *,meshgrid在2d数组中布局网格点:行对应于不同的y值,列对应于不同的x值-如list(list((x, y) for x in xs) for y in ys),这将给予以下数组:
[[(1,4), (2,4), (3,4)],
    [(1,5), (2,5), (3,5)],
    [(1,6), (2,6), (3,6)]]
  • 其次 *,meshgrid分别返回x和y坐标(即在两个不同的numpy 2d数组中):
xcoords, ycoords = (
       array([[1, 2, 3],
              [1, 2, 3],
              [1, 2, 3]]),
       array([[4, 4, 4],
              [5, 5, 5],
              [6, 6, 6]]))
   # same thing using np.meshgrid:
   xcoords, ycoords = np.meshgrid([1,2,3], [4,5,6])
   # same thing without meshgrid:
   xcoords = np.array([xs] * len(ys)
   ycoords = np.array([ys] * len(xs)).T

注意,np.meshgrid也可以生成更高维度的网格。给定xs,ys和zs,你会得到xcoords,ycoords,zcoords作为3d数组。meshgrid还支持维度的逆序以及结果的稀疏表示。

应用

为什么我们需要这种形式的输出?

  • 在网格上的每一点上应用一个函数:* 一个动机是像(+,-,*,/,**)这样的二元运算符被重载为numpy数组作为元素操作。这意味着,如果我有一个函数def f(x, y): return (x - y) ** 2,它适用于两个标量,我也可以将它应用于两个numpy数组,以获得一个元素级结果的数组:例如,f(xcoords, ycoords)f(*np.meshgrid(xs, ys))给出了上面示例的以下内容:
array([[ 9,  4,  1],
       [16,  9,  4],
       [25, 16,  9]])
  • 高维外积:* 我不确定这有多有效,但你可以这样得到高维外积:np.prod(np.meshgrid([1,2,3], [1,2], [1,2,3,4]), axis=0)
  • matplotlib中的等高线图:* 我在研究drawing contour plots with matplotlib绘制决策边界时遇到了meshgrid。为此,您使用meshgrid生成网格,在每个网格点处评估函数(例如,如上所示),然后传递xcoords、ycoords和计算的f值(即,zcoords)到contourf函数中。
4ngedf3f

4ngedf3f8#

幕后:

import numpy as np

def meshgrid(x , y):
    XX = []
    YY = []
    for colm in range(len(y)):
        XX.append([])
        YY.append([])
        for row in range(len(x)):
            XX[colm].append(x[row])
            YY[colm].append(y[colm])
    return np.asarray(XX), np.asarray(YY)

让我们以@Sarsaparilla的answer数据集为例:

y = [7, 6, 5]
x = [1, 2, 3, 4]

xx, yy = meshgrid(x , y)

并且其输出:

>>> xx
array([[1, 2, 3, 4],
       [1, 2, 3, 4],
       [1, 2, 3, 4]])

>>> yy
array([[7, 7, 7, 7],
       [6, 6, 6, 6],
       [5, 5, 5, 5]])
ztigrdn8

ztigrdn89#

要在NumPy中构造数组的直积,我们可以使用meshgrid函数。它创建二维数组,其中包含两个原始数组中元素的所有可能组合。

import numpy as np

# create two arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# get direct product of arrays
product = np.array(np.meshgrid(arr1, arr2)).T.reshape(-1, 2)
print(product)

然后我们得到:

[[1 4]
 [1 5]
 [1 6]
 [2 4]
 [2 5]
 [2 6]
 [3 4]
 [3 5]
 [3 6]]

相关问题