Numpy等效的zip与滚动的2D数组

时间:2017-02-23 04:29:23

标签: python numpy coordinates

我有一个2D坐标列表作为NumPy数组,例如

x = np.asarray([[0, 1],
                [1, 2],
                [2, 3]])

形状(3,2)

现在我想用np.roll(x, 1)压缩这个数组,以获得坐标对之间的线条(包括从最后一个元素到第一个元素的线条。线条的顺序无关紧要。

我已经找到了使用标准Python zip的解决方案:

>>> np.asarray(list(zip(list(x[-1:]) + list(x[:-1]), x)))
array([[[2, 3],
        [0, 1]],
       [[0, 1],
        [1, 2]],
       [[1, 2],
        [2, 3]]])

如何在不转换为Python列表的情况下使用numpy函数来获得此结果?

到目前为止,我对NumPy的尝试失败了,例如:

>>> np.dstack([x, np.roll(x, 1)])
array([[[0, 3],
        [1, 0]],

       [[1, 1],
        [2, 1]],

       [[2, 2],
        [3, 2]]])

编辑:这不是尝试创建 x 与任何其他数组的组合,因此建议的副本不重复。

2 个答案:

答案 0 :(得分:1)

我不太明白为什么这是你想要的输出,但这是你想要获得的dstack版本:

>>> np.transpose(np.dstack([np.roll(x, 1, axis=0), x]), axes=(0,2,1))
array([[[2, 3],
        [0, 1]],

       [[0, 1],
        [1, 2]],

       [[1, 2],
        [2, 3]]])

答案 1 :(得分:1)

这是一种创建此类滚动索引然后编制索引的方法 -

In [18]: x            # Input array
Out[18]: 
array([[0, 1],
       [1, 2],
       [2, 3]])

In [19]: n = x.shape[0]

In [20]: x[np.mod(np.arange(n)[:,None] + [n-1,0],n)]
Out[20]: 
array([[[2, 3],
        [0, 1]],

       [[0, 1],
        [1, 2]],

       [[1, 2],
        [2, 3]]])