Michael Michael - 1 month ago 5
Python Question

Get rid of a dimension by concatenating into another dimension

Suppose I have a 3D Numpy array:

a = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])


Now, I'd like to get rid of dimension 0, by concatenating the elements along current dimension 1 (= new dimension 0). So I'd end up with the following array:

[[0, 1], [2, 3], [4, 5], [6, 7]]


(I might also want to do this along another dimension.)

Basically, it's no big deal to do it with
reshape
, but it requires some manual size calculation. Is there a convenience function to do it directly?

Answer

One approach would be with np.vstack as it stacks vertically (row wise) -

np.vstack(a)

Even np.concatenate works too as by default it concatenates along the first axis -

np.concatenate(a)

Stating the reshaping based one too for completeness -

a.reshape(-1,a.shape[-1])
Comments