Vectorize numpy array expansion

后端 未结 4 2013
被撕碎了的回忆
被撕碎了的回忆 2021-01-15 02:38

I\'m trying to find a way to vectorize an operation where I take 1 numpy array and expand each element into 4 new points. I\'m currently doing it with Python loop. First l

4条回答
  •  [愿得一人]
    2021-01-15 02:50

    For the first example, you can use np.kron

    >>> a = np.array([0, 1, 1, 0])
    >>> np.kron(input_array, a)
    array([0, 1, 1, 0, 0, 2, 2, 0, 0, 3, 3, 0, 0, 4, 4, 0])
    

    For the second example, you can use np.repeat and np.tile

    >>> b = np.array([-0.2, -0.2, 0.2, 0.2])
    >>> np.repeat(input_array, b.size) + np.tile(b, input_array.size)
    array([ 0.8,  0.8,  1.2,  1.2,  1.8,  1.8,  2.2,  2.2,  2.8,  2.8,  3.2,
            3.2,  3.8,  3.8,  4.2,  4.2])
    

提交回复
热议问题