np.concatenate a ND tensor/array with a 1D array

前端 未结 4 1625
南笙
南笙 2021-01-14 09:33

I have two arrays a & b

a.shape
(5, 4, 3)
array([[[ 0.        ,  0.        ,  0.        ],
        [ 0.        ,  0.        ,  0.        ],
        [ 0.          


        
4条回答
  •  臣服心动
    2021-01-14 10:11

    You can use np.repeat:

    r = np.concatenate((a, b.reshape(1, 1, -1).repeat(a.shape[0], axis=0)), axis=1)
    

    What this does, is first reshape your b array to match the dimensions of a, and then repeat its values as many times as needed according to a's first axis:

    b3D = b.reshape(1, 1, -1).repeat(a.shape[0], axis=0)
    
    array([[[1, 2, 3]],
    
           [[1, 2, 3]],
    
           [[1, 2, 3]],
    
           [[1, 2, 3]],
    
           [[1, 2, 3]]])
    
    b3D.shape
    (5, 1, 3)
    

    This intermediate result is then concatenated with a -

    r = np.concatenate((a, b3d), axis=0)
    
    r.shape
    (5, 5, 3)
    

    This differs from your current answer mainly in the fact that the repetition of values is not hard-coded (i.e., it is taken care of by the repeat).

    If you need to handle this for a different number of dimensions (not 3D arrays), then some changes are needed (mainly in how remove the hardcoded reshape of b).


    Timings

    a = np.random.randn(100, 99, 100)
    b = np.random.randn(100)
    

    # Tai's answer
    %timeit np.insert(a, 4, b, axis=1)
    100 loops, best of 3: 3.7 ms per loop
    
    # Divakar's answer
    %%timeit 
    b3D = np.broadcast_to(b,(a.shape[0],1,len(b)))
    np.concatenate((a,b3D),axis=1)
    
    100 loops, best of 3: 3.67 ms per loop
    
    # solution in this post
    %timeit np.concatenate((a, b.reshape(1, 1, -1).repeat(a.shape[0], axis=0)), axis=1)
    100 loops, best of 3: 3.62 ms per loop
    

    These are all pretty competitive solutions. However, note that performance depends on your actual data, so make sure you test things first!

提交回复
热议问题