3

So let's say that I have an array like so:

[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
]

I am attempting to stack every 2 arrays together, so I end up with the following:

 [
 [[1, 2, 3], [1, 2, 3]],
 [[1, 2, 3], [1, 2, 3]],
 ]

It is especially important for this to be as efficient as possible as this will be running on hardware that is not too powerful, so I would prefer to do this without looping through the array. Is there a way to implement this in numpy without using loops? Thank you in advance.

1 Answer 1

3

Provided your first dimension is even (multiple of 2), you can use reshape to convert your 2-D array to 3-D array as following. The only thing here is to use the first dimension as int(x/2) where x is the first dimension of your 2-D array and the second dimension as 2. It is important to convert to int because the shape argument has to be of integer type.

arr_old = np.array([
               [1, 2, 3],
               [1, 2, 3],
               [1, 2, 3],
               [1, 2, 3],
               ])

x, y = arr_old.shape # The shape of this input array is (4, 3)

arr_new = arr_old.reshape(int(x/2), 2, y) # Reshape the old array

print (arr_new.shape)  
# (2, 2, 3)

print (arr_new)

# [[[1 2 3]
#  [1 2 3]]

# [[1 2 3]
#  [1 2 3]]]    

As pointed out by @orli in comments, you can also do

arr_old.shape = (x//2, 2, y)
Sign up to request clarification or add additional context in comments.

2 Comments

note that you're creating a new array that way so if you care about memory efficiency as well, it's better to use: arr_old.shape = (x//2, 2, y)
@orli: Thanks for the nice suggestion. I added it to my answer

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.