【问题标题】:Select rows in a numpy array where there are no "holes", the holes being 0 (example ...,1,0,1,...)选择没有“孔”的numpy数组中的行,孔为0(例如...,1,0,1,...)
【发布时间】:2021-05-26 17:35:55
【问题描述】:

如何在 numpy 数组中选择没有“孔”的行,孔为 0。例如,如果我的输入是:

M = np.array([[0,10,0,20,30],[15,0,0,25,35],[0,40,40,40,0],[50,0,50,0,50]])

我希望输出是:

M = np.array([[15,0,0,25,35],[0,40,40,40,0]]) 

第一行和最后一行没有被选中,因为它们的序列“非零整数,0,非零整数”

【问题讨论】:

    标签: python arrays numpy select filter


    【解决方案1】:

    我认为convolution可以用来检测漏洞。

    首先将每个非零转换为1,将零转换为0。所以在像101这样的地方,带有窗口[1,1,1]convolution中心索引将是1*1 + 1*0 + 1*1 = 2。所以如果我们检查所有零位置,如果卷积矩阵的值是@987654328 @我们可以检测孔状况。

    import numpy as np
    
    M = np.array([[0,10,0,20,30],[15,0,0,25,35],[0,40,40,40,0],[50,0,50,0,50]])
    
    M_ =  M.astype(bool).astype(int)
    convolved = np.apply_along_axis(lambda x: np.convolve(x, [1,1,1], 'same'), 1, M_)
    output = M[list(set(range(len(M_))).difference(np.where((convolved == 2) & (M_==0))[0]))]
    
    print(output)
    
    [[15  0  0 25 35]
     [ 0 40 40 40  0]]
    

    【讨论】:

      【解决方案2】:

      要检测一行中的“洞”,请定义以下函数:

      def hasHole(row):
          wrk = np.vstack([np.roll(row, -1), (row == 0).astype(int), np.roll(row, 1)])[:, 1:-1]
          return np.not_equal(wrk, 0).all(0).any()
      

      然后,要查找带有孔的行的布尔索引,请运行:

      idx = np.apply_along_axis(hasHole, axis=1, arr=M)
      

      最后,为了得到预期的结果,运行:

      result = M[~idx]
      

      结果是:

      array([[15,  0,  0, 25, 35],
             [ 0, 40, 40, 40,  0]])
      

      【讨论】:

        猜你喜欢
        • 2012-12-17
        • 2013-03-27
        • 1970-01-01
        • 1970-01-01
        • 2021-10-17
        • 1970-01-01
        • 2016-08-07
        • 2017-12-19
        • 2015-11-28
        相关资源
        最近更新 更多