I have two numpy arrays with three dimensions (3 x 4 x 5) and I want to concatenate them so the result has four dimensions (3 x 4 x 5 x 2). In Matlab, this can be done with cat(4, a, b)
, but not in Numpy.
For example:
a = ones((3,4,5)) b = ones((3,4,5)) c = concatenate((a,b), axis=3) # error!
To clarify, I wish c[:,:,:,0]
and c[:,:,:,1]
to correspond to the original two arrays.
You can either reshape it array_2. reshape(-1,1) , or add a new axis array_2[:,np. newaxis] to make it 2 dimensional before concatenation.
Joining Arrays Using Stack FunctionsWe can concatenate two 1-D arrays along the second axis which would result in putting them one over the other, ie. stacking. We pass a sequence of arrays that we want to join to the stack() method along with the axis.
numpy. dstack stack the array along the third axis, so, if you stack 3 arrays ( a , b , c ) of shape (N,M) , you'll end up with an array of shape (N,M,3) . That gives you a (3,N,M) array. Pierre, many thanks for your answer, I will test this option in my project.
In general numpy arrays can have more than one dimension. One way to create such array is to start with a 1-dimensional array and use the numpy reshape() function that rearranges elements of that array into a new shape.
Here you go:
import numpy as np a = np.ones((3,4,5)) b = np.ones((3,4,5)) c = np.concatenate((a[...,np.newaxis],b[...,np.newaxis]),axis=3)
What about
c = np.stack((a,b), axis=3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With