pythonappend

How can I append two arrays, but have the second array in wide format?


If I have two arrays in python:

Array 1 =

[[1 2]
 [3 4]]

Array 2 = 
[[5 6]] 

How can I use .append or .extend to create an array, such that:

Array 3:
[[1 2 5 6]
 [3 4 5 6]]

Solution

  • Assuming you have numpy arrays, you can broadcast the second array to the shape of the first, and concatenate along the second axis with:

    array1 = np.array([[1,2],[3,4]])
    array2 = np.array([5,6])
    
    np.c_[array1, np.broadcast_to(array2, array1.shape)]
    
    array([[1, 2, 5, 6],
           [3, 4, 5, 6]])