【问题标题】:How to get numpy sub-array view when array ndim is not known until runtime?当数组 ndim 直到运行时才知道时,如何获取 numpy 子数组视图?
【发布时间】:2013-03-28 07:20:27
【问题描述】:

我有一个形状为M x N x ... x T 的 Python numpy N 维数组,但直到运行时我才知道数组的维数(秩)。

如何创建该数组的子数组的视图,由两个具有长度等级的向量指定:extentoffset? 将 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, ... ] 条目。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    如果我理解正确,请使用

    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]]]])
    

    【讨论】:

    • 是的!你有我的意图是正确的。该代码看起来对我有用。所以slice 是新的,但我认为它代表a:b 符号?
    • @NoahR:是的,见the documentation
    猜你喜欢
    • 2010-09-30
    • 2011-08-18
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 2013-11-10
    • 2017-03-26
    相关资源
    最近更新 更多