Search code examples
numpy-ndarraylinspace

np.where() with np.linspace()


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.


Solution

  • 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.