简体   繁体   中英

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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