1

I have two 2D numpy arrays:

a = np.array([[0,1,2,3,4],
              [0,1,2,3,4],
              [0,1,2,3,4]
              ...
              ])

b = np.array([[0,0,0,0,0],
              [1,1,1,1,1],
              [2,2,2,2,2],
              ...
              ])

How would I be able to get a numpy array where each exact index will concatenate together?

OUT:
[[0,0], [1,0], [2,0], [3,0], [4,0] [0,1], [1,1], [2,1], [3,1], [4,1] ...]
2
  • The two sample arrays don't have the same shape. How do you expect to pair them index-wise? That is, what do you do with un-aligned indexes? Commented Feb 25, 2021 at 16:02
  • Apologies, you are right, I did not write the input correctly Edit: I have made the two sample arrays of the same shape - the initial question stays the same! Commented Feb 25, 2021 at 16:04

3 Answers 3

2

You want stack

result = np.stack((a,b), axis=2)
array([[[0, 0],
        [1, 0],
        [2, 0],
        [3, 0],
        [4, 0]],

       [[0, 1],
        [1, 1],
        [2, 1],
        [3, 1],
        [4, 1]],

       [[0, 2],
        [1, 2],
        [2, 2],
        [3, 2],
        [4, 2]]])

Taken from @user15270287, you can reshape the results with np.reshape(result, (-1, 2))

Sign up to request clarification or add additional context in comments.

1 Comment

To get a 2d array like you want you can do np.reshape(result, (-1, 2)) after this
2

You can use np.dstack:

>>> a = np.array([[0,1,2,3,4],
              [0,1,2,3,4],
              [0,1,2,3,4]
              ])

>>> b = np.array([[0,0,0,0,0],
              [1,1,1,1,1],
              [2,2,2,2,2],
              ])

>>> np.dstack((a, b)).reshape(-1, 2)
array([[0, 0],
       [1, 0],
       [2, 0],
       [3, 0],
       [4, 0],
       [0, 1],
       [1, 1],
       [2, 1],
       [3, 1],
       [4, 1],
       [0, 2],
       [1, 2],
       [2, 2],
       [3, 2],
       [4, 2]])

Comments

0
def mapper(x):
    temp = []
    for a,b in zip(x[0],x[1]):
        temp.append([a,b])
    return temp

result = list(map(lambda x:mapper(x),zip(a,b)))

Output:

[[[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]],
 [[0, 1], [1, 1], [2, 1], [3, 1], [4, 1]],
 [[0, 2], [1, 2], [2, 2], [3, 2], [4, 2]]]

Comments

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.