【问题标题】:How to get a subarray in numpy如何在numpy中获取子数组
【发布时间】:2015-07-18 04:45:21
【问题描述】:

我有一个 3d 数组,我想获得一个以索引 indx 为中心的大小为 (2n+1) 的子数组。使用我可以使用的切片

y[slice(indx[0]-n,indx[0]+n+1),slice(indx[1]-n,indx[1]+n+1),slice(indx[2]-n,indx[2]+n+1)]

如果我想为每个维度设置不同的尺寸,这只会变得更丑。有没有更好的方法来做到这一点。

【问题讨论】:

    标签: numpy sub-array


    【解决方案1】:

    您不需要使用slice 构造函数,除非您想存储切片对象以供以后使用。相反,您可以这样做:

    y[indx[0]-n:indx[0]+n+1, indx[1]-n:indx[1]+n+1, indx[2]-n:indx[2]+n+1]
    

    如果您想在不单独指定每个索引的情况下执行此操作,可以使用列表推导:

    y[[slice(i-n, i+n+1) for i in indx]]
    

    【讨论】:

    • 应该是逗号而不是冒号 y[[slice(i-n,i+n+1) for i in indx]]。除此之外,谢谢
    • @user3799584:谢谢,错字已修正!
    【解决方案2】:

    您可以创建 numpy 数组以索引到 3D array 的不同维度,然后使用 ix_ function 创建索引映射,从而获得切片输出。 ix_ 的好处是它允许广播索引地图。有关这方面的更多信息,请访问 here。然后,您可以为通用解决方案的每个维度指定不同的窗口大小。这是带有示例输入数据的实现 -

    import numpy as np
    
    A = np.random.randint(0,9,(17,18,16))  # Input array
    indx = np.array([5,10,8])              # Pivot indices for each dim
    N = [4,3,2]                            # Window sizes
    
    # Arrays of start & stop indices
    start = indx - N
    stop = indx + N + 1
    
    # Create indexing arrays for each dimension
    xc = np.arange(start[0],stop[0])
    yc = np.arange(start[1],stop[1])
    zc = np.arange(start[2],stop[2])
    
    # Create mesh from multiple arrays for use as indexing map 
    # and thus get desired sliced output
    Aout = A[np.ix_(xc,yc,zc)]
    

    因此,对于具有窗口大小数组的给定数据,N = [4,3,2]whos 信息显示 -

    In [318]: whos
    Variable   Type       Data/Info
    -------------------------------
    A          ndarray    17x18x16: 4896 elems, type `int32`, 19584 bytes
    Aout       ndarray    9x7x5: 315 elems, type `int32`, 1260 bytes
    

    输出的whos 信息Aout 似乎与必须为2N+1 的预期输出形状一致。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-06
      • 2018-09-11
      • 2018-01-26
      • 1970-01-01
      • 2021-06-03
      • 2017-03-15
      • 2019-11-07
      • 2020-05-19
      相关资源
      最近更新 更多