简体   繁体   English

从左侧或右侧用非零值填充一维 NumPy 数组的零值?

[英]Fill Zero values of 1D NumPy Array with non-zero value from left or right?

I have an array that typically has zero's at the beginning and end (and occasionally in the middle).我有一个数组,通常在开头和结尾(偶尔在中间)都有零。

I want to fill the zeros with the first value found on the left or right of the array.我想用在数组左侧或右侧找到的第一个值填充零。

array = [0, 0, 0, 1, 3, 5, 0, 4, 2, 0, 0, 0]

I want ideally:理想情况下,我想要:

new_array = [1, 1, 1, 1, 3, 5, (5 or 4), 4, 2, 2, 2, 2]

How can I accomplish this?我怎样才能做到这一点?

You can try this:你可以试试这个:

import numpy as np

array = [0, 0, 0, 1, 3, 5, 0, 4, 2, 0, 0, 0]
# nonzero indices in array
nz = np.nonzero(array)[0]

# add element to a list if nonzero otherwise get its closest nonzero element
[x if x else array[nz[np.argmin(np.abs(i-nz))]] for i, x in enumerate(array)]
>>> [1, 1, 1, 1, 3, 5, 5, 4, 2, 2, 2, 2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM