0

I have a 2 numpy arrays in the following format

array([[2, 2, 7, 1],
 [5, 0, 3, 1],
 [2, 9, 8, 8],
 [5, 7, 7, 6]])

and

array([[1, 2, 3, 4],
 [5, 6, 7, 8],
 [9, 10, 11, 12],
 [13, 14, 15, 16]])

I want to combine these to the following format

array([[[2, 2, 7, 1],[1,2,3,4]],
 [[5, 0, 3, 1],[5,6,7,8]],
 [[2, 9, 8, 8],[9,10,11,12]],
 [[5, 7, 7, 6],[13,14,15,16]]])

The real data which I am handling contains very large amount of data(5000 in one row). SO working with pandas doesnt solve the case. Is there any efficient method when the data is very huge for creating a format like this

asked Jan 2, 2022 at 8:48
3
  • My bad... corrected now Commented Jan 2, 2022 at 8:59
  • I think you are looking for np.stack with appropriate axis argument, e.g. np.stack((array1, array2), axis=1). Commented Jan 2, 2022 at 9:00
  • Yeah. Thanks :) Commented Jan 2, 2022 at 9:01

1 Answer 1

5

You are looking for stack

arr1 = np.array([[2, 2, 7, 1],
 [5, 0, 3, 1],
 [2, 9, 8, 8],
 [5, 7, 7, 6]])
arr2 = np.array([[1, 2, 3, 4],
 [5, 6, 7, 8],
 [9, 10, 11, 12],
 [13, 14, 15, 16]])
arr3 = np.stack((arr1, arr2), axis=1)
print(arr3)

Output

[[[ 2 2 7 1]
 [ 1 2 3 4]]
 [[ 5 0 3 1]
 [ 5 6 7 8]]
 [[ 2 9 8 8]
 [ 9 10 11 12]]
 [[ 5 7 7 6]
 [13 14 15 16]]]
answered Jan 2, 2022 at 9:00
Sign up to request clarification or add additional context in comments.

2 Comments

@imhans33, if that works, please accept it as the correct answer.
acceted.. pls upvote the qs too

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.