Vectorize numpy array expansion

后端 未结 4 2060
被撕碎了的回忆
被撕碎了的回忆 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:56

    For the first example, you can do an outer product of the input and the template and reshape the result:

    input_array = np.array([1, 2, 3, 4])
    template = np.array([0, 1, 1, 0])
    
    np.multiply.outer(input_array, template)
    # array([[0, 1, 1, 0],
    #        [0, 2, 2, 0],
    #        [0, 3, 3, 0],
    #        [0, 4, 4, 0]])
    
    result = np.multiply.outer(input_array, template).ravel()
    # array([0, 1, 1, 0, 0, 2, 2, 0, 0, 3, 3, 0, 0, 4, 4, 0])
    

    Similarly for your second example you can use np.add.outer

    np.add.outer(input_array, [-0.2, -0.2, 0.2, 0.2]).ravel()
    # 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])
    

    See:

    • http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.outer.html

提交回复
热议问题