Reputation: 5126
I am trying to map 2 numpy arrays as [x, y] similar to what zip does for lists and tuples.
I have 2 numpy arrays as follows:
arr1 = [1, 2, 3, 4]
arr2 = [5, 6, 7, 8]
I am looking for an output as np.array([[[1, 5], [2, 6], [3, 7], [4, 8]]])
I tried this but it maps every value and not with same indices. I can add more if conditions here but is there any other way to do so without adding any more if conditions.
res = [arr1, arr2] for a1 in arr1 for a2 in arr2]
Upvotes: 4
Views: 961
Reputation: 51165
You are looking for np.dstack
Stack arrays in sequence depth wise (along third axis).
np.dstack([arr1, arr2])
array([[[1, 5],
[2, 6],
[3, 7],
[4, 8]]])
Upvotes: 3
Reputation: 43494
IIUC, one way is to use numpy.vstack()
followed by transpose()
:
import numpy as np
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([5, 6, 7, 8])
print(np.vstack([arr1, arr2]).transpose())
#array([[1, 5],
# [2, 6],
# [3, 7],
# [4, 8]])
Or you could pass the output of zip
to the array
constructor:
print(np.array(zip(arr1, arr2)))
#array([[1, 5],
# [2, 6],
# [3, 7],
# [4, 8]])
Upvotes: 2
Reputation: 736
The built in zip
command is the job for you here. It'll do exactly what you're asking.
arr1 = [1,2,3,4]
arr2 = [5,6,7,8]
list(zip(arr1, arr2))
[(1, 5), (2, 6), (3, 7), (4, 8)]
https://docs.python.org/3/library/functions.html#zip
Upvotes: 0