【问题标题】:Fill a 3D numpy array with ones based on a 2D array with indices用基于带索引的 2D 数组的数组填充 3D numpy 数组
【发布时间】:2018-03-08 02:36:34
【问题描述】:

我有 2 个 numpy 数组 outputindex

output = np.zeros((3,3,3))

>>>index   
array([[0,1,2],
       [1,0,0],
       [2,2,2]])

index 表示索引,直到output 应填充第一维中的索引。 output 的填充值应如下所示:

>>>output 
array([[[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]],
       [[0, 1, 1],
        [1, 0, 0],
        [1, 1, 1]],
       [[0, 0, 1],
        [0, 0, 0],
        [1, 1, 1]]] 

例如,由于index[0, 1] == 1,我们设置output[:1+1, 0, 1] = 1。一般来说,如果index[i, j] == k,我们设置output[:k+1, i, j] = 1

有谁知道如何以矢量化的方式实现这一点?

【问题讨论】:

    标签: python arrays numpy multidimensional-array indexing


    【解决方案1】:

    使用NumPy broadcasting,我们可以创建这些地方的掩码。因此,只需将该掩码转换为 0s1s 的 int 数组,就像这样 -

    (index >= np.arange(3)[:,None,None]).astype(int)
    

    示例运行 -

    In [471]: index
    Out[471]: 
    array([[0, 1, 2],
           [1, 0, 0],
           [2, 2, 2]])
    
    In [472]: (index >= np.arange(3)[:,None,None]).astype(int)
    Out[472]: 
    array([[[1, 1, 1],
            [1, 1, 1],
            [1, 1, 1]],
    
           [[0, 1, 1],
            [1, 0, 0],
            [1, 1, 1]],
    
           [[0, 0, 1],
            [0, 0, 0],
            [1, 1, 1]]])
    

    或者,要分配给output,请使用boolean-indexing 的掩码并分配1s -

    output[index >= np.arange(output.shape[0])[:,None,None]] = 1
    

    【讨论】:

      【解决方案2】:

      您可以将1 分配给最后一个位置(沿第一个维度),然后使用np.maximum.accumulate 将0 填充为1:

      output[index, np.arange(output.shape[1])[:,None], np.arange(output.shape[2])] = 1  
      np.maximum.accumulate(output[::-1], axis=0)[::-1]
      
      #array([[[ 1.,  1.,  1.],
      #        [ 1.,  1.,  1.],
      #        [ 1.,  1.,  1.]],
      
      #       [[ 0.,  1.,  1.],
      #        [ 1.,  0.,  0.],
      #        [ 1.,  1.,  1.]],
      
      #       [[ 0.,  0.,  1.],
      #        [ 0.,  0.,  0.],
      #        [ 1.,  1.,  1.]]])
      

      【讨论】:

        猜你喜欢
        • 2019-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多