假设我们有一个填充了一些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和 …