NoahR
NoahR

Reputation: 1467

How to get numpy sub-array view when array ndim is not known until runtime?

I have a Python numpy N-dimensional array with shape M x N x ... x T, but I do not know the number of dimensions (rank) of the array until runtime.

How can I create a view of a sub-array of that array, specified by two vectors with length rank: extent and offset? import numpy as np

def select_subrange( orig_array, subrange_extent_vector, subrange_offset_vector ):
    """
    returns a view of orig_array offset by the entries in subrange_offset_vector
    and with extent specified by entries in subrange_extent_vector.
    """
    # ??? 
    return subarray

I'm stuck because the slicing examples I have found require [ start:end, ... ] entries for each array dimension.

Upvotes: 1

Views: 862

Answers (1)

BrenBarn
BrenBarn

Reputation: 251538

If I understand you right, use

orig_array[[slice(o, o+e) for o, e in zip(offset, extent)]]

Example:

>>> x = np.arange(4**4).reshape((4, 4, 4, 4))
>>> x[0:2, 1:2, 2:3, 1:3]
array([[[[25, 26]]],


       [[[89, 90]]]])
>>> offset = (0, 1, 2, 1)
>>> extent = (2, 1, 1, 2)
>>> x[[slice(o, o+e) for o, e in zip(offset, extent)]]
array([[[[25, 26]]],


       [[[89, 90]]]])

Upvotes: 3

Related Questions