Vectorize numpy array expansion

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

    It seems you want to want to do elementwise operations between input_array and the array that contains the extending elements. For these, you can use broadcasting.

    For the first example, it seems you are performing elementwise multiplication -

    In [424]: input_array = np.array([1, 2, 3, 4])
         ...: extend_array = np.array([0, 1, 1, 0])
         ...: 
    
    In [425]: (input_array[:,None] * extend_array).ravel()
    Out[425]: array([0, 1, 1, 0, 0, 2, 2, 0, 0, 3, 3, 0, 0, 4, 4, 0])
    

    For the second example, it seems you are performing elementwise addition -

    In [422]: input_array = np.array([1, 2, 3, 4])
         ...: extend_array = np.array([-0.2, -0.2, 0.2, 0.2])
         ...: 
    
    In [423]: (input_array[:,None] + extend_array).ravel()
    Out[423]: 
    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])
    

提交回复
热议问题