python - How to get numpy sub-array view when array ndim is not known until runtime? -
i have python numpy n-dimensional array shape m x n x ... x t
, not know number of dimensions (rank) of array until runtime.
how can create view of sub-array of array, specified 2 vectors length rank: extent
, offset
? import numpy np
def select_subrange( orig_array, subrange_extent_vector, subrange_offset_vector ): """ returns view of orig_array offset entries in subrange_offset_vector , extent specified entries in subrange_extent_vector. """ # ??? return subarray
i'm stuck because slicing examples have found require [ start:end, ... ]
entries each array dimension.
if understand right, use
orig_array[[slice(o, o+e) 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) o, e in zip(offset, extent)]] array([[[[25, 26]]], [[[89, 90]]]])
Comments
Post a Comment