I have a 2d array with shape (x, y) which I want to convert to a 3d array with shape (x, y, 1). Is there a nice Pythonic way to do this?
A three dimensional means we can use nested levels of array for each dimension. To create a 3-dimensional numpy array we can use simple numpy. array() function to display the 3-d array.
In addition to the other answers, you can also use slicing with numpy.newaxis
:
>>> from numpy import zeros, newaxis >>> a = zeros((6, 8)) >>> a.shape (6, 8) >>> b = a[:, :, newaxis] >>> b.shape (6, 8, 1)
Or even this (which will work with an arbitrary number of dimensions):
>>> b = a[..., newaxis] >>> b.shape (6, 8, 1)
numpy.reshape(array, array.shape + (1,))
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