Find boolean mask by pattern

前端 未结 2 1940
一生所求
一生所求 2020-12-11 07:37

I have array:

arr = np.array([1,2,3,2,3,4,3,2,1,2,3,1,2,3,2,2,3,4,2,1])
print (arr)
[1 2 3 2 3 4 3 2 1 2 3 1 2 3 2 2 3 4 2 1]

I would like

2条回答
  •  伪装坚强ぢ
    2020-12-11 07:58

    Not sure how safe this is, but another method would be to read back to an as_strided view of the boolean output. As long as you only have one pat at a time it shouldn't be a problem I think, and it may work with more but I can't gurantee it because reading back to as_strided can be a bit unpredictable:

    def vview(a):  #based on @jaime's answer: https://stackoverflow.com/a/16973510/4427777
        return np.ascontiguousarray(a).view(np.dtype((np.void, a.dtype.itemsize * a.shape[1])))
    
    def roll_mask(arr, pat):
        pat = np.atleast_2d(pat)
        out = np.zeros_like(arr).astype(bool)
        vout = rolling_window(out, pat.shape[-1])
        vout[np.in1d(vview(rolling_window(arr, pat.shape[-1])), vview(pat))] = True
        return out
    
    np.where(roll_mask(arr, pat))
    (array([ 0,  1,  2,  8,  9, 10, 11, 12, 13], dtype=int32),)
    
    pat = np.array([[1, 2, 3], [3, 2, 3]])
    print([i for i in arr[roll_mask(arr, pat)]])
    [1, 2, 3, 2, 3, 1, 2, 3, 1, 2, 3]
    

    It seems to work, but I wouldn't give this answer to a beginner!

提交回复
热议问题