Consider, for reference:
>>> x, y = np.ones((2, 2, 2)), np.zeros((2, 2, 2))
>>> np.concatenate((x, y, x, y), axis=2)
array([[[ 1., 1., 0., 0., 1., 1., 0., 0.],
[ 1., 1., 0., 0., 1., 1., 0., 0.]],
[[ 1., 1., 0., 0., 1., 1., 0., 0.],
[ 1., 1., 0., 0., 1., 1., 0., 0.]]])
We have stacked the arrays along the innermost dimension, merging it - the resulting shape is (2, 2, 8)
. But suppose I wanted those innermost elements to lie side-by-side instead (this would only work because every dimension of the source arrays is the same, including the one I want to 'stack' in), producing a result with shape (2, 2, 4, 2)
as follows?
array([[[[ 1., 1.],
[ 0., 0.],
[ 1., 1.],
[ 0., 0.]],
[[ 1., 1.],
[ 0., 0.],
[ 1., 1.],
[ 0., 0.]]],
[[[ 1., 1.],
[ 0., 0.],
[ 1., 1.],
[ 0., 0.]],
[[ 1., 1.],
[ 0., 0.],
[ 1., 1.],
[ 0., 0.]]]])
The best approach I have is to reshape each source array first, to add a 1-length dimension right before the last:
def pad(npa):
return npa.reshape(npa.shape[:-1] + (1, npa.shape[-1]))
np.concatenate((pad(x), pad(y), pad(x), pad(y)), axis=2) # does what I want
# np.hstack might be better? I always want the second-last dimension, now
But I feel like I am reinventing a wheel. Have I overlooked something that will do this more directly?