The accepted answer above is great. But I'll add the following because I'm a math dork and it's a nice use of the fact that a.shape
is a.T.shape[::-1]
...i.e. taking a transpose reverses the order of the indices of a numpy array. So if you have your building blocks in an array called blocks, then the solution above is:
new = np.concatenate([block[..., np.newaxis] for block in blocks],
axis=len(blocks[0].shape))
but you could also do
new2 = np.array([block.T for block in blocks]).T
which I think reads more cleanly. It's worth noting that the already-accepted answer runs more quickly:
%%timeit
new = np.concatenate([block[..., np.newaxis] for block in blocks],
axis=len(blocks[0].shape))
1000 loops, best of 3: 321 µs per loop
while
%%timeit
new2 = np.array([block.T for block in blocks]).T
1000 loops, best of 3: 407 µs per loop