1

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.

1 Answer 1

3

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]]]])
Sign up to request clarification or add additional context in comments.

2 Comments

Yes! You have my intent correct. The code looks to be working for me. So slice is new, but I gather that represents the a:b notation?
@NoahR: Yes, see the documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.