2

I am trying to find index of an element in x_norm array with np.where() but it doesn' t work well. Is there a way to find index of element?

x_norm  = np.linspace(-10,10,1000)
np.where(x_norm == -0.19019019)

Np.where works with np.arange() and can find the index either first or last element of array creating by linspace.

madracoon
  • 23
  • 2

2 Answers2

0

The numbers generated by np.linspace contains more decimal places than the one you are pasting to np.where (-0.19019019019019012).

So it might be better to use np.argmin to find the nearest value and avoid rounding errors:

x_norm  = np.linspace(-10,10,1000)
yournumber=-0.19019019
idx=np.argmin(np.abs(x_norm-yournumber))

You can then go further and add np.where(x_norm==x_norm[idx]) to your code in case if you'll have array with duplicates.

YevKad
  • 650
  • 6
  • 13
0

Set the level of precision to 8 using np.round then use np.where to filter data as a mask then apply the mask to the array.

x_norm  = np.round(np.asarray(np.linspace(-10,10,1000)),8)
results=x_norm[np.where(x_norm==-9.91991992)]
print(results)
Golden Lion
  • 3,840
  • 2
  • 26
  • 35