mrsulaj
mrsulaj

Reputation: 397

Stack every 2 arrays in 2D array using numpy without loops

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.

Upvotes: 3

Views: 80

Answers (1)

Sheldore
Sheldore

Reputation: 39062

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)

Upvotes: 3

Related Questions