NumPy mgrid成元组

时间:2015-04-12 05:17:26

标签: numpy

如何从给定的NumPy数组(xx和yy)获得结果?

>>> xx, yy = np.mgrid[0:2, 5:7]
>>> xx
array([[0, 0],
       [1, 1]])
>>> yy
array([[5, 6],
       [5, 6]])
>>> result = [(0,5), (1,5), (1,6), (0,6)]
>>> result
[(0, 5), (1, 5), (1, 6), (0, 6)]
>>> 

1 个答案:

答案 0 :(得分:1)

您的示例中的顺序需要一些xx的精美索引。我不得不颠倒第二列的顺序。

In [243]: np.array([np.array([xx[:,0], xx[::-1,1]]).flatten(), yy.T.flatten()]).T.tolist()
Out[243]: [[0, 5], [1, 5], [1, 6], [0, 6]]

如果订单不是那么重要,那么我们可以像xx一样对待yy

In [256]: xx, yy = np.mgrid[0:3, 5:8]

In [257]: np.array([xx.T.flatten(),yy.T.flatten()]).T.tolist()
Out[257]: [[0, 5], [1, 5], [2, 5], [0, 6], [1, 6], [2, 6], [0, 7], [1, 7], [2, 7]]

In [258]: np.array([xx.flatten(),yy.flatten()]).T.tolist()
Out[258]: [[0, 5], [0, 6], [0, 7], [1, 5], [1, 6], [1, 7], [2, 5], [2, 6], [2, 7]]

In [264]: np.array([xx,yy]).reshape(2,-1).T.tolist()
Out[264]: [[0, 5], [0, 6], [0, 7], [1, 5], [1, 6], [1, 7], [2, 5], [2, 6], [2, 7]]

In [272]: np.dstack([xx,yy]).reshape(-1,2).tolist()
Out[272]: [[0, 5], [0, 6], [0, 7], [1, 5], [1, 6], [1, 7], [2, 5], [2, 6], [2, 7]]

In [302]: list(np.broadcast(*np.ogrid[0:3,5:8]))
Out[302]: [(0, 5), (0, 6), (0, 7), (1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7)]