Search code examples
pythonnumpymultidimensional-arrayconcatenationelementwise-operations

Concatenate the nested arrays within a single 2d array, element-wise


I have a numpy array like this:

array = [[1, 3, 5, 7], [2, 4, 6, 8]]

I would like to concatenate them element-wise. Most of the solutions I have found are able to do this with two separate 2d arrays, but I would like to do this within a single 2d array.

Desired output:

array = [[1, 2], [3, 4], [5, 6], [7, 8]]

Solution

  • Just only line code

    array = [[1, 3, 5, 7], [2, 4, 6, 8]]
    print(list(zip(*array)))
    

    output :

    [(1, 2), (3, 4), (5, 6), (7, 8)]