1

I would like to combine N arrays of shape (I, J) into a single array of shape (I, J, N) such that the value at (i, j, n) in the final array is equal to the value of the n-th array at (i, j).

For example, let's say I have two arrays:

arr1 = [[2,3,4],
        [3,4,5]]

arr2 = [[3,4,2],
         [4,3,5]]

Then the final array would look like:

arr_final == [[[2,3], [3,4], [4,2]], 
              [[3,4], [4,3], [5,5]]]

Or, to take a more straightforward example:

arr1 = [[0,0,0],
        [0,0,0]]

arr2 = [[1,1,1],
         [1,1,1]]

arr3 = [[2,2,2],
         [2,2,2]]

Then the final array would look like:

arr_final == [[[0,1,2], [0,1,2], [0,1,2]], 
              [[0,1,2], [0,1,2], [0,1,2]]]

Is there a function in Python, or more specifically Numpy, that could help me with this?

1
  • What does np.array((arr1, arr2)) produce? A (2,i,j)? That's the usual way of combining N arrays. Commented Jan 25, 2023 at 19:29

1 Answer 1

1

In Numpy, you can use numpy.stack. Remember to specify the axis as -1 in order to get it to correctly compose it as you want according to your question.

import numpy as np

arr_final = np.stack([arr1, arr2, ..., arrN], axis=-1)

will produce the desired outcome.

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

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.