Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 961
mrsulaj Avatar asked Dec 01 '25 05:12

mrsulaj


1 Answers

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)
like image 134
Sheldore Avatar answered Dec 03 '25 22:12

Sheldore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!