相关疑难解决方法(0)

使用最后的非零值填充1d numpy数组的零值

假设我们有一个填充了一些int值的1d numpy数组.让我们说其中一些是0.

有没有办法,使用numpy数组的功能,0用找到的最后一个非零值填充所有值?

例如:

arr = np.array([1, 0, 0, 2, 0, 4, 6, 8, 0, 0, 0, 0, 2])
fill_zeros_with_last(arr)
print arr

[1 1 1 2 2 4 6 8 8 8 8 8 2]
Run Code Online (Sandbox Code Playgroud)

一种方法是使用此功能:

def fill_zeros_with_last(arr):
    last_val = None # I don't really care about the initial value
    for i in range(arr.size):
        if arr[i]:
            last_val = arr[i]
        elif last_val is not None:
            arr[i] = last_val
Run Code Online (Sandbox Code Playgroud)

但是,这是使用原始python for循环而不是利用numpy和 …

python numpy

11
推荐指数
2
解决办法
3296
查看次数

标签 统计

numpy ×1

python ×1