Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving the dimensions of a slice from a Numpy 3d array

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.

like image 862
Brendan Avatar asked Apr 14 '10 18:04

Brendan


People also ask

How do I flatten the size of a NumPy array?

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 .

How do you flatten a 3D matrix in Python?

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.

Can you slice NumPy arrays?

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.


1 Answers

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).

like image 182
unutbu Avatar answered Sep 21 '22 06:09

unutbu