I have a 3d array, a
, of shape say a.shape = (10, 10, 10)
When slicing, the dimensions are squeezed
automatically i.e.
a[:,:,5].shape = (10, 10)
I'd like to preserve the number of dimensions but also ensure that the dimension that was squeezed is the one that shows 1 i.e.
a[:,:,5].shape = (10, 10, 1)
I have thought of re-casting the array and passing ndmin
but that just adds the extra dimensions to the start of the shape tuple regardless of where the slice came from in the array a
.
Flatten a NumPy array with reshape(-1) You can also use reshape() to convert the shape of a NumPy array to one dimension. If you use -1 , the size is calculated automatically, so you can flatten a NumPy array with reshape(-1) . reshape() is provided as a method of numpy. ndarray .
By using ndarray. flatten() function we can flatten a matrix to one dimension in python. order:'C' means to flatten in row-major. 'F' means to flatten in column-major.
Slicing in python means extracting data from one given index to another given index, however, NumPy slicing is slightly different. Slicing can be done with the help of (:) . A NumPy array slicing object is constructed by giving start , stop , and step parameters to the built-in slicing function.
a[:,:,[5]].shape
# (10,10,1)
a[:,:,5]
is an example of basic slicing.
a[:,:,[5]]
is an example of integer array indexing -- combined with basic slicing. When using integer array indexing the resultant shape is always "identical to the (broadcast) indexing array shapes". Since [5]
(as an array) has shape (1,)
,
a[:,:,[5]]
ends up having shape (10,10,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