numpyreshape

Converting two 2d arrays of different shapes into a 3d array


How to convert two 2d arrays of shapes (629, 5) and (629, 6) into a 3d array of shape (629, 5, 6)?

Input:

[[2, 5, 6, 7, 8],
 [3, 5, 6, 7, 8],
 [4, 5, 6, 7, 8]]

[[2, 5, 6, 7, 8, 9],
 [3, 5, 6, 7, 8, 9],
 [4, 5, 6, 7, 8, 9]]

Output:

[[[2, 5, 6, 7, 8, 9], [2, 5, 6, 7, 8, 9], [2, 5, 6, 7, 8, 9], [2, 5, 6, 7, 8, 9], [2, 5, 6, 7, 8, 9]], 
 [[3, 5, 6, 7, 8, 9], [3, 5, 6, 7, 8, 9], [3, 5, 6, 7, 8, 9], [3, 5, 6, 7, 8, 9], [3, 5, 6, 7, 8, 9]], 
 [[4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9]]]

Solution

  • If you just want to broadcast arr2 you could use broadcast_to:

    arr1 = np.array([[2, 5, 6, 7, 8],
                     [3, 5, 6, 7, 8],
                     [4, 5, 6, 7, 8]])
    arr2 = np.array([[2, 5, 6, 7, 8, 9],
                     [3, 5, 6, 7, 8, 9],
                     [4, 5, 6, 7, 8, 9]])
    
    out = np.broadcast_to(arr2[:,None], (*arr1.shape, arr2.shape[1]))
    

    or numpy.repeat:

    out = np.repeat(arr2[:,None], arr1.shape[1], axis=1)
    

    Output:

    # shape: (3, 5, 6)
    array([[[2, 5, 6, 7, 8, 9],
            [2, 5, 6, 7, 8, 9],
            [2, 5, 6, 7, 8, 9],
            [2, 5, 6, 7, 8, 9],
            [2, 5, 6, 7, 8, 9]],
    
           [[3, 5, 6, 7, 8, 9],
            [3, 5, 6, 7, 8, 9],
            [3, 5, 6, 7, 8, 9],
            [3, 5, 6, 7, 8, 9],
            [3, 5, 6, 7, 8, 9]],
    
           [[4, 5, 6, 7, 8, 9],
            [4, 5, 6, 7, 8, 9],
            [4, 5, 6, 7, 8, 9],
            [4, 5, 6, 7, 8, 9],
            [4, 5, 6, 7, 8, 9]]])