NumPy条件下的向前填充

3

我有一个像这样的numpy数组,里面都是0。

a = np.array([3., 0., 2., 3., 0., 3., 3., 3., 0., 3., 3., 0., 3., 0., 0., 0., 0.,
   3., 3., 0., 3., 3., 0., 3., 0., 3., 0., 0., 0., 3., 0., 3., 3., 0.,
   3., 3., 0., 0., 3., 0., 0., 0., 3., 0., 3., 3., 3., 3., 3., 3., 3.,
   3., 3., 3., 3., 3., 3., 4., 3., 0., 3., 3., 3., 3., 3., 3., 3., 0.,
   0., 0., 0., 3., 0., 0., 3., 0., 0., 0., 3., 3., 3., 3., 3., 3., 3.,
   3., 0., 3., 3., 3., 3., 3., 0., 3., 3., 3., 3., 0., 0., 0., 3., 3.,
   3., 0., 3., 3., 3., 5., 3., 3., 3., 3., 3., 3., 3., 0., 3., 0., 3.,
   3., 0., 0., 0., 3., 3., 3., 3., 0., 3., 3., 3., 3., 3., 3., 3., 3.,
   3., 3., 3., 3., 0., 3., 3., 3., 3., 3., 3., 0., 3., 3., 3., 3., 3.,
   3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 0., 3., 0., 3.,
   3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 0., 3., 3., 3., 3.,
   3., 3., 3., 3., 3., 3., 3., 3., 0., 3., 3., 0., 0., 3., 0., 0., 3.,
   0., 3., 3., 0., 3., 3., 0., 0., 3., 3., 3., 3., 3., 3., 3., 0., 3.,
   3., 3., 3., 3.])

我需要在某种条件下用前一个数值替换零值(向前填充)。如果两个非零数之间的零值数量小于或等于2,则需要向前填充零。

例如:

1)如果我考虑这三个数字:3.,0.,2.,那么两个非零数之间的零个数为1。这应该由3进行填充。

2)如果我考虑这些数字:3.,0.,0.,0.,0.,3.,3.,则3之间的零数大于2,因此它将保持不变。

3个回答

2
在这些情况下,如果仅使用向量化方法似乎不太容易(至少在这种情况下),我们可以使用 numba 将您的代码编译成 C级别。以下是一种使用 numba 的 nopython 模式的方法:
import numba

@numba.njit('int64[:](int64[:],uintc)') #change accordingly
def conditional_ffill(a, w):
    c=0
    last_non_zero = a[0]
    out = np.copy(a)
    for i in range(len(a)):
        if a[i]==0:
            c+=1
        elif c>0 and c<w:
            out[i-c:i] = last_non_zero
            c=0
            last_non_zero=a[i]
    return out

查看divakar的测试数组:

a = np.array([2, 0, 3, 0, 0, 4, 0, 0, 0, 5, 0])

conditional_ffill(a, w=1)
# array([2, 0, 3, 0, 0, 4, 0, 0, 0, 5, 0])

conditional_ffill(a, w=2)
# array([2, 2, 3, 0, 0, 4, 0, 0, 0, 5, 0])

conditional_ffill(a, w=3)
# array([2, 2, 3, 3, 3, 4, 0, 0, 0, 5, 0])

conditional_ffill(a, w=4)
# array([2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 0])

在更大的数组上运行时间:

a_large = np.tile(a, 10000)

%timeit ffill_windowed(a_large, 3)
# 1.39 ms ± 68.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit conditional_ffill(a_large, 3)
# 150 µs ± 862 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

1
这里提供一种方法,使用向前填充窗口作为参数来处理通用情况 -
# https://stackoverflow.com/a/33893692/ @Divakar
def numpy_binary_closing(mask,W):
    # Define kernel
    K = np.ones(W)

    # Perform dilation and threshold at 1
    dil = np.convolve(mask,K)>=1

    # Perform erosion on the dilated mask array and threshold at given threshold
    dil_erd = np.convolve(dil,K)>= W
    return dil_erd[W-1:-W+1]

def ffill_windowed(a, W):
    mask = a!=0
    mask_ext = numpy_binary_closing(mask,W)

    p = mask_ext & ~mask
    idx = np.maximum.accumulate(mask*np.arange(len(mask)))
    out = a.copy()
    out[p] = out[idx[p]]
    return out
解释: 第一部分执行的是二进制闭合操作,在图像处理领域中得到了很好的探索。因此,在我们的情况下,我们将从非零掩模开始,并基于窗口参数进行图像封闭。通过获取前向填充索引(在this post中有介绍),我们可以获得需要填充的所有位置的索引。我们根据先前获得的封闭掩模放入新值。就是这样!

示例运行-

In [142]: a
Out[142]: array([2, 0, 3, 0, 0, 4, 0, 0, 0, 5, 0])

In [143]: ffill_windowed(a, W=2)
Out[143]: array([2, 2, 3, 0, 0, 4, 0, 0, 0, 5, 0])

In [144]: ffill_windowed(a, W=3)
Out[144]: array([2, 2, 3, 3, 3, 4, 0, 0, 0, 5, 0])

In [146]: ffill_windowed(a, W=4)
Out[146]: array([2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 0])

1
这个很好用。感谢@Divakar提供的精彩答案。这真的是一个很好的学习曲线。 - Rajith Thennakoon

0

我无法想象一种向量化的方法,所以我只是寻找了一种过程式的方法:

def ffill(arr, mx):
    """Forward fill 0 values in arr with a max of mx consecutive 0 values"""
    first = None                     # first index of a sequence of 0 to fill
    prev = None                      # previous value to use
    for i, val in enumerate(arr):
        if val == 0.:                # process a null value
            if prev is not None:
                if first is None:
                    first = i
                elif i - first >= mx:   # to much consecutive 0: give up
                    prev = None
                    first = None
        else:
            if first is not None:    # there was a sequence to fill 
                arr[first:i] = prev
                first = None

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接