Home > Software design >  Concatenate the nested arrays within a single 2d array, element-wise
Concatenate the nested arrays within a single 2d array, element-wise

Time:01-01

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]]

CodePudding user response:

ljdyer is almost right, but you have only one array, so you can do this:

list(zip(*array))

CodePudding user response:

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)]

CodePudding user response:

This is a zip operation. Try:

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

Output:

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

Or for numpy arrays you have the stack operation:

import numpy as np

a = np.array([1, 3, 5, 7])
b = np.array([2, 4, 6, 8])

c = np.stack((a,b), axis = 1)

print(c)

See https://www.delftstack.com/howto/numpy/python-numpy-zip/

CodePudding user response:

The following code will concatenate array element wise in each column

import numpy as np

array = np.array([[1, 3, 5, 7], [2, 4, 6, 8]])
res = []
for i in range(array.shape[1]):
  res.append(array[:, i])
res = np.array(res)
print(res.tolist())
  • Related