Tuesday, 15 March 2011

Python: Index an array using the colon operator in an arbitrary dimension -



Python: Index an array using the colon operator in an arbitrary dimension -

i have numpy nd array. simplified version of task take vector along each axis. illustrate:

import numpy x = numpy.array(range(24)).reshape((2,3,4)) x0 = x[0,0,:] x1 = x[0,:,0] x2 = x[:,0,0]

however not know number of dimensions x have. challenge how place colon : indexing operator in variable location. illustration of such syntax like:

n = x.ndim ind = list(np.zeros(n)) dim = 0 ind[dim] = ':' y = x[ind]

or

y = indexer.index(x,ind)

for module indexer. write it, sense must solved, can't 1 wants this. in matlab, example, can subsref() function.

does such build exist in python / numpy / other module?

as suggested numpy's documentation indexing can utilize slice built-in function , tuple concatenation create variable indexes.

in fact : in subscript literal notation slice literal.

in particular : equivalent slice(none) (which, itself, equivalent slice(none, none, none) arguments start, stop , step).

for example:

a[(0,) * n + (slice(none),)]

is equivalent to:

a[0, 0, ..., 0, :] # n zeros

the : notation slices can used straight within subscript. illustration fails:

in [10]: a[(0,0,:)] file "<ipython-input-10-f41b33bd742f>", line 1 a[(0,0,:)] ^ syntaxerror: invalid syntax

to allow extracting piece array of arbitrary dimensions can write simple function such as:

def make_index(num_dimension, slice_pos): zeros = [0] * num_dimension zeros[slice_pos] = slice(none) homecoming tuple(zeros)

and utilize in:

in [3]: = np.array(range(24)).reshape((2, 3, 4)) in [4]: a[make_index(3, 2)] out[4]: array([0, 1, 2, 3]) in [5]: a[make_index(3, 1)] out[5]: array([0, 4, 8]) in [6]: a[make_index(3, 0)] out[6]: array([ 0, 12])

you can generalize make_index kind of things. of import thing remember should, in end, homecoming tuple containing either integers or slices.

python arrays numpy colon matrix-indexing

No comments:

Post a Comment