Replace NaN's in NumPy array with closest non-NaN value

前端 未结 7 1723
你的背包
你的背包 2021-02-05 04:22

I have a NumPy array a like the following:

>>> str(a)
\'[        nan         nan         nan  1.44955726  1.44628034  1.44409573\\n  1.4408         


        
7条回答
  •  抹茶落季
    2021-02-05 05:08

    I want to replace each NaN with the closest non-NaN value... there will be no NaN's in the middle of the numbers

    The following will do it:

    ind = np.where(~np.isnan(a))[0]
    first, last = ind[0], ind[-1]
    a[:first] = a[first]
    a[last + 1:] = a[last]
    

    This is a straight numpy solution requiring no Python loops, no recursion, no list comprehensions etc.

提交回复
热议问题