If k is an numpy array of an arbitrary shape, so k.shape = (s1, s2, s3, ..., sn)
, and I want to reshape it so that k.shape
becomes (s1, s2, ..., sn, 1)
, is this the best way to do it in one line?
k.reshape(*(list(k.shape) + [1])
You can add new dimensions to a NumPy array ndarray (= unsqueeze a NumPy array) with np. newaxis , np. expand_dims() and np. reshape() (or reshape() method of ndarray ).
With the help of Numpy. expand_dims() method, we can get the expanded dimensions of an array by using Numpy. expand_dims() method. Return : Return the expanded array.
Creating arrays with more than one dimensionIn 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.
The shape of the array can also be changed using the resize() method. If the specified dimension is larger than the actual array, The extra spaces in the new array will be filled with repeated copies of the original array.
It's easier like this:
k.reshape(k.shape + (1,))
But if all you want is to add an empty dimension at the end, you should use numpy.newaxis
:
import numpy as np k = k[..., np.newaxis]
or
k = k[..., None]
(See the documentation on slicing).
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