代码之家  ›  专栏  ›  技术社区  ›  bFig8

Numpy交错连接阵列

  •  2
  • bFig8  · 技术社区  · 7 年前

    我有4个数组,我想通过交错将它们连接成一个数组。我该怎么做?

    >>> import numpy as np
    >>> a = np.tile(0,(5,2))
    >>> b = np.tile(1,(5,2))
    >>> c = np.tile(2,(5,2))
    >>> d = np.tile(3,(5,2))
    >>> e = np.concatenate((a,b,c,d),axis=1)
    >>> e
        array([[0, 0, 1, 1, 2, 2, 3, 3],
               [0, 0, 1, 1, 2, 2, 3, 3],
               [0, 0, 1, 1, 2, 2, 3, 3],
               [0, 0, 1, 1, 2, 2, 3, 3],
               [0, 0, 1, 1, 2, 2, 3, 3]])
    

    这只提供了连接。

    然而,我想要的_输出是:

    >>> desired_output
        array([[0, 1, 2, 3, 0, 1, 2, 3],
               [0, 1, 2, 3, 0, 1, 2, 3],
               [0, 1, 2, 3, 0, 1, 2, 3],
               [0, 1, 2, 3, 0, 1, 2, 3],
               [0, 1, 2, 3, 0, 1, 2, 3]])
    

    我的意思是我知道我可以使用以下方法从e中选择交错列:

    >>> f = e[:, ::2]
    >>> array([[0, 1, 2, 3],
               [0, 1, 2, 3],
               [0, 1, 2, 3],
               [0, 1, 2, 3],
               [0, 1, 2, 3]])
    

    但是我如何制作一个大数组呢?

    1 回复  |  直到 7 年前
        1
  •  5
  •   Divakar    7 年前

    使用 np.dstack np.stack 沿着最后一个轴堆叠,这给了我们一个 3D 2D -

    np.dstack([a,b,c,d]).reshape(a.shape[0],-1)
    np.stack([a,b,c,d],axis=2).reshape(a.shape[0],-1)