Python: retrieving a single slice of a multidimensional array based on a dimension index

I know how to take x[:,:,:,:,j,:] (which takes the jth piece of dimension 4).

Is there a way to do the same if the measurement is known at run time and is not a known constant?

+6
source share
3 answers

You can use the slice function and call it with the appropriate list of variables at runtime as follows:

 # Store the variables that represent the slice in a list/tuple # Make a slice with the unzipped tuple using the slice() command # Use the slice on your array 

Example:

 >>> from numpy import * >>> a = (1, 2, 3) >>> b = arange(27).reshape(3, 3, 3) >>> s = slice(*a) >>> b[s] array([[[ 9, 10, 11], [12, 13, 14], [15, 16, 17]]]) 

This is the same as:

 >>> b[1:2:3] array([[[ 9, 10, 11], [12, 13, 14], [15, 16, 17]]]) 

Finally, the equivalent of not specifying anything between 2 : in conventional notation, is to put None in those places in the created tuple.

+6
source

One option to do this is programmatically:

 slicing = (slice(None),) * 4 + (j,) + (slice(None),) 

An alternative is to use numpy.take() or ndarray.take() :

 >>> a = numpy.array([[1, 2], [3, 4]]) >>> a.take((1,), axis=0) array([[3, 4]]) >>> a.take((1,), axis=1) array([[2], [4]]) 
+8
source

You can also use ellipsis to replace duplicate colons. See the answer to How to use the ellipsis cut syntax in Python? for example.

0
source

Source: https://habr.com/ru/post/919267/


All Articles