Ad

Printing Array Indices With The Corresponding Value In Python

- 1 answer

I have a problem in printing array indices with the value I want to find. I'm getting just the first indices and then not the others.

I have tried with the np.where function but It won't work so I had to make a loop manually.

Here's the code:

g = 0.34
while g <= 0.97: 
        idx = []
        for i in range (0, y2.size):
            if y2[i] == g:
                idx.append(i)
        print(idx)
        g = g + 0.01

This is what I have:

[92, 376]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
.....

The array has 500 values from 0.34 to 0.97. Same output with np.where(y2 == g) without the loop.

Ad

Answer

You are running into float inaccuracies. See also this post that deals specifically with that issue. In short, this is what happens in your code:

>>>g = 0.34
>>>g = g + 0.01
>>>g
Out: 0.35000000000000003   

The result 0.35000000000000003 will no longer evaluate to true if compared with 0.35. Try using np.isclose instead, as it deals with these minor inaccuracies:

>>>import numpy as np
>>>g = 0.34
>>>g = g + 0.01
>>>g==0.35
Out: False
>>>np.isclose(g,0.35)
Out: True

You can even use it in combination with np.where to get your original approach to work:

>>>import numpy as np
>>>g = 0.34
>>>y2 = np.array([0.37, 0.38, 0.37, 0.35, 0.34, 0.34])
>>>np.where(np.isclose(y2,g))
Out: (array([4, 5], dtype=int64),)
>>>g = g + 0.01
>>>np.where(np.isclose(y2,g))
Out: (array([3], dtype=int64),)
Ad
source: stackoverflow.com
Ad