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

前端 未结 7 1714
你的背包
你的背包 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:14

    Here is a solution using simple python iterators. They are actually more efficient here than numpy.where, especially with big arrays! See comparison of similar code here.

    import numpy as np
    
    a = np.array([np.NAN, np.NAN, np.NAN, 1.44955726, 1.44628034, 1.44409573, 1.4408188, 1.43657094, 1.43171624,  1.42649744, 1.42200684, 1.42117704, 1.42040255, 1.41922908, np.NAN, np.NAN, np.NAN, np.NAN, np.NAN, np.NAN])
    
    mask = np.isfinite(a)
    
    # get first value in list
    for i in range(len(mask)):
        if mask[i]:
            first = i
            break
    
    # get last vaue in list
    for i in range(len(mask)-1, -1, -1):
        if mask[i]:
            last = i
            break
    
    # fill NaN with near known value on the edges
    a = np.copy(a)
    a[:first] = a[first]
    a[last + 1:] = a[last]
    
    print(a)
    

    Output:

    [1.44955726 1.44955726 1.44955726 1.44955726 1.44628034 1.44409573
     1.4408188  1.43657094 1.43171624 1.42649744 1.42200684 1.42117704
     1.42040255 1.41922908 1.41922908 1.41922908 1.41922908 1.41922908
     1.41922908 1.41922908]
    

    It replaces only the first and last NaNs like requested here.

提交回复
热议问题