解开一个 numpy mgrid
Un-ravel an numpy mgrid
假设我有一个网格定义如下:
x,y = np.mgrid[0:5:5j, 0:5:5j]
根据this answer,我可以通过执行以下操作转到坐标列表:
coords = np.vstack((x.ravel(),y.ravel())).T
如何从坐标中return到x,y值,例如:
x,y = foo(coords)
你有没有费心打印 x,y
?
In [58]: x,y = np.mgrid[0:5:1j, 0:5:1j]
In [59]: x
Out[59]: array([[0.]])
In [60]: y
Out[60]: array([[0.]])
In [61]: coords = np.vstack((x.ravel(),y.ravel())).T
In [62]: coords
Out[62]: array([[0., 0.]])
与1j
,它在每个维度生成1个元素。 2个数组然后是(1,1)形状,并组合(1,2)。
让数组变得更有趣
In [63]: x,y = np.mgrid[0:5:1, 0:5:1]
In [64]: x
Out[64]:
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]])
In [65]: y
Out[65]:
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
这些是 (5,5)。
In [66]: coords = np.vstack((x.ravel(),y.ravel())).T
In [67]: coords
Out[67]:
array([[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[1, 0],
...
[4, 4]])
In [68]: _.shape
Out[68]: (25, 2)
由于您已将它们加入列中,我们可以通过索引取回 x
;并且因为我们有 'raveled' 他们,我们可以 reshape
回到 (5,5) 与:
In [69]: coords[:,0].reshape(5,5)
Out[69]:
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]])
连接 2 个数组的另一种方法:
In [70]: np.stack((x,y), axis=-1).shape
Out[70]: (5, 5, 2)
可以重新整形以匹配 coords
:
In [71]: np.allclose(np.stack((x,y), axis=-1).reshape(-1,2), coords)
Out[71]: True
还有更多重塑游戏来自:)
ravel
只是重塑为 1d:
In [72]: np.allclose(x.ravel(), x.reshape(25))
Out[72]: True
所以 reshape(5,5)
是显而易见的解开。
假设我有一个网格定义如下:
x,y = np.mgrid[0:5:5j, 0:5:5j]
根据this answer,我可以通过执行以下操作转到坐标列表:
coords = np.vstack((x.ravel(),y.ravel())).T
如何从坐标中return到x,y值,例如:
x,y = foo(coords)
你有没有费心打印 x,y
?
In [58]: x,y = np.mgrid[0:5:1j, 0:5:1j]
In [59]: x
Out[59]: array([[0.]])
In [60]: y
Out[60]: array([[0.]])
In [61]: coords = np.vstack((x.ravel(),y.ravel())).T
In [62]: coords
Out[62]: array([[0., 0.]])
与1j
,它在每个维度生成1个元素。 2个数组然后是(1,1)形状,并组合(1,2)。
让数组变得更有趣
In [63]: x,y = np.mgrid[0:5:1, 0:5:1]
In [64]: x
Out[64]:
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]])
In [65]: y
Out[65]:
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
这些是 (5,5)。
In [66]: coords = np.vstack((x.ravel(),y.ravel())).T
In [67]: coords
Out[67]:
array([[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[1, 0],
...
[4, 4]])
In [68]: _.shape
Out[68]: (25, 2)
由于您已将它们加入列中,我们可以通过索引取回 x
;并且因为我们有 'raveled' 他们,我们可以 reshape
回到 (5,5) 与:
In [69]: coords[:,0].reshape(5,5)
Out[69]:
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]])
连接 2 个数组的另一种方法:
In [70]: np.stack((x,y), axis=-1).shape
Out[70]: (5, 5, 2)
可以重新整形以匹配 coords
:
In [71]: np.allclose(np.stack((x,y), axis=-1).reshape(-1,2), coords)
Out[71]: True
还有更多重塑游戏来自:)
ravel
只是重塑为 1d:
In [72]: np.allclose(x.ravel(), x.reshape(25))
Out[72]: True
所以 reshape(5,5)
是显而易见的解开。