Mainland
Mainland

Reputation: 4564

Finding nearest value in a numpy array produces nan output

I have a list. I want to find the value closest to a given number. Everything is working fine. But the problem is, it produces nan output for two unique numbers. Here I am providing my complete data

My code and output:

#### Find the index of nearest value in a array
def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx] #for returing nearest value 

r = [0.209272  , 0.172816  , 0.1297975 , 0.0777895 , 0.008605  ,
          np.nan,        np.nan,        np.nan,        np.nan,        np.nan]

rc = 0.38420566666666667
rse_ed = find_nearest(r,0.01) ### close to 0.01 is 0.008605
rse_st = find_nearest(r,rc*0.4) #### close to 0.15368226666666668 is 0.172816
print(rse_st,rse_ed)
nan,nan  ### 

Expected output:

print(rse_st,rse_ed)
0.172816,0.008605

Upvotes: 0

Views: 364

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545578

Use nanargmin:

def find_nearest(array, value):
    array = np.asarray(array)
    idx = np.nanargmin(np.abs(array - value))
    return array[idx]

Upvotes: 3

Related Questions