我有一个形状为M x N x ... x T
的Python numpy n维数组,但直到运行时我才知道数组的维数(秩)。
如何创建该数组的子数组的视图,由两个长度为秩的向量指定:extent
和offset
?导入numpy为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
我卡住了,因为我发现切片示例需要每个数组维度的[ start:end, ... ]
条目。
如果我理解对了,请使用
orig_array[[slice(o, o+e) for o, e in zip(offset, extent)]]
的例子:
>>> 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]]]])