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

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

    As an alternate solution (this will linearly interpolate for arrays NaNs in the middle, as well):

    import numpy as np
    
    # Generate data...
    data = np.random.random(10)
    data[:2] = np.nan
    data[-1] = np.nan
    data[4:6] = np.nan
    
    print data
    
    # Fill in NaN's...
    mask = np.isnan(data)
    data[mask] = np.interp(np.flatnonzero(mask), np.flatnonzero(~mask), data[~mask])
    
    print data
    

    This yields:

    [        nan         nan  0.31619306  0.25818765         nan         nan
      0.27410025  0.23347532  0.02418698         nan]
    
    [ 0.31619306  0.31619306  0.31619306  0.25818765  0.26349185  0.26879605
      0.27410025  0.23347532  0.02418698  0.02418698]
    

提交回复
热议问题