np.where returns wrong index

Viewed 278

I use a nested list wl_list. And I want to find an index of the minimal residue between 0.21 and the second value in the list. To demonstrate what I mean, look at this:

In [107]: wl_list 
Out[107]: 
[[0.21, 0.20033118267365396],
 [0.21, 0.20108968331942148],
 [0.21, 0.2018455976996333],
 [0.21, 0.20259889407493714],
 [0.21, 0.20334954134171523],
 [0.21, 0.20409750903553264],
 [0.21, 0.20484276733424645],
 [0.21, 0.20558528706077894],
 [0.21, 0.2063250396855564],
 [0.21, 0.20706199732861758],
 [0.21, 0.20779613276139344],
 [0.21, 0.20852741940816347]]

In [108]: np.diff(wl_list)
Out[108]: 
array([[-0.00966882],
       [-0.00891032],
       [-0.0081544 ],
       [-0.00740111],
       [-0.00665046],
       [-0.00590249],
       [-0.00515723],
       [-0.00441471],
       [-0.00367496],
       [-0.002938  ],
       [-0.00220387],
       [-0.00147258]])

In [109]: np.min(np.abs(np.diff(wl_list)))
Out[109]: 0.0014725805918365253

Then I want to use np.where to get essentially the last index in this case, but what I get instead is this:

In [110]: np.where(np.min(np.abs(np.diff(wl_list))))
Out[110]: (array([0]),)

In [111]: i = np.where(np.min(np.abs(np.diff(wl_list))))[0][0]

In [112]: wl_list[i]
Out[112]: [0.21, 0.20033118267365396]

I don't understand this behavior, could you please explain what do I do wrong? Thanks.

1 Answers

You can use argmin here (in the case where the minimum value could be repeated, it would return the first match):

ix = np.abs(np.diff(wl_list)).argmin()
# 11
wl_list[ix]
# array([0.21      , 0.20852742])

np.where gives you the indices where a condition is satisfied, i.e. where there are Trues in an array. Your input though, is just the result of np.min(...). That won't give you the index where the value takes place in the array.

Related