0

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]]
Npstork12
  • 13
  • 1
  • 1
    Is `array` a numpy array, or a list of lists? Looks like you just want the array transpose. `list(zip(*...)` js a list version of transpose. – hpaulj Jan 01 '22 at 07:41

5 Answers5

1

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)]
Jay Patel
  • 1,098
  • 7
  • 22
0

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/

ljdyer
  • 1,946
  • 1
  • 3
  • 11
  • Unfortunately, I am trying not to split it into separate arrays. I'd like to do this to the nested arrays within a single 2d array. – Npstork12 Jan 01 '22 at 07:20
0

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

list(zip(*array))
Francisco
  • 10,918
  • 6
  • 34
  • 45
0

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())
Vignesh
  • 302
  • 3
  • 12
0

Numpy transpose:

In [382]: np.transpose([[1, 3, 5, 7], [2, 4, 6, 8]])
Out[382]: 
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])

If it already is a numpy array (as opposed to just a list of lists),you can use the T shortcut:

In [383]: arr = np.array([[1, 3, 5, 7], [2, 4, 6, 8]])
In [384]: arr
Out[384]: 
array([[1, 3, 5, 7],
       [2, 4, 6, 8]])
In [385]: arr.T
Out[385]: 
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])

list-zip is a well known list version of transpose:

In [386]: list(zip(*arr))
Out[386]: [(1, 2), (3, 4), (5, 6), (7, 8)]

Note the result is a list of tuples.

hpaulj
  • 221,503
  • 14
  • 230
  • 353