Extend numpy mask by n cells to the right for each bad value, efficiently

前端 未结 7 1343
[愿得一人]
[愿得一人] 2021-02-15 15:39

Let\'s say I have a length 30 array with 4 bad values in it. I want to create a mask for those bad values, but since I will be using rolling window functions, I\'d also like a f

7条回答
  •  逝去的感伤
    2021-02-15 15:54

    You can use np.ufunc.reduceat with np.bitwise_or:

    import numpy as np
    a = np.array([4, 0, 8, 5, 10, 9, np.nan, 1, 4, 9, 9, np.nan, np.nan, 9,
                  9, 8, 0, 3, 7, 9, 2, 6, 7, 2, 9, 4, 1, 1, np.nan, 10])
    m = np.isnan(a)
    n = 4
    i = np.arange(1, len(m)+1)
    ind = np.column_stack([i-n, i]) # may be a faster way to generate this
    ind.clip(0, len(m)-1, out=ind)
    
    np.bitwise_or.reduceat(m, ind.ravel())[::2]
    

    On your data:

    print np.column_stack([m, reduced])
    [[False False]
     [False False]
     [False False]
     [False False]
     [False False]
     [False False]
     [ True  True]
     [False  True]
     [False  True]
     [False  True]
     [False False]
     [ True  True]
     [ True  True]
     [False  True]
     [False  True]
     [False  True]
     [False False]
     [False False]
     [False False]
     [False False]
     [False False]
     [False False]
     [False False]
     [False False]
     [False False]
     [False False]
     [False False]
     [False False]
     [ True  True]
     [False  True]]
    

提交回复
热议问题