4

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]
1
  • Do you want a (1,4,2) array? 3d with that initial size 1 dimension. Commented Jun 20, 2018 at 22:11

3 Answers 3

3

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]]])
Sign up to request clarification or add additional context in comments.

7 Comments

I did not know this existed +1
It's numpy, something always exists ;)
Thanks @user3483203. I tried the above and I am getting without comma-separated values.
yeah my input is of this type <class 'numpy.ndarray'>
Oh that's just how your stdout represents a numpy array. The values are separated, don't worry :) Try converting to a list if you want to verify
|
2

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

Comments

0

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

1 Comment

good approach, but OP is looking for a method specific to numpy.ndarray parameters and returns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.