Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: extracting one slice of a multidimensional array given the dimension index

Tags:

python

numpy

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

Is there a way to do the same thing if the dimension is known at runtime, and is not a known constant?

like image 846
Jason S Avatar asked Jun 28 '12 16:06

Jason S


2 Answers

One option to do so is to construct the slicing programatically:

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]])
like image 86
Sven Marnach Avatar answered Nov 15 '22 20:11

Sven Marnach


You can use the slice function and call it with the appropriate variable list during 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 the usual notation is to put None in those places in the tuple you create.

like image 37
Dhara Avatar answered Nov 15 '22 20:11

Dhara