How can I find the indices of an array with float values in python?

MRAB python at mrabarnett.plus.com
Thu Jan 10 13:39:30 EST 2019


On 2019-01-10 17:05, Madhavan Bomidi wrote:
> Sorry for re-posting with a correction.
> 
> I have an array (numpy.ndarray) with shape (1500L,) as below:
>   
>   x = array([  3.00000000e+01,   6.00000000e+01,   9.00000000e+01, ...,
>            4.49400000e+04,   4.49700000e+04,   4.50000000e+04])
>   
> Now, I wanted to determine the indices of the x values between 0.0 and 15000.0. While this is simple in MATLAB or IDL by using find or where functions, I was unable to find a best way to find the indices of all elements between 0.0 and 15000.0 in the x array. Can you please suggest me a solution for the same?
> 
I don't know if there's a better way, but:

 >>> import numpy as np
 >>> x = np.array([  3.00000000e+01,   6.00000000e+01,   9.00000000e+01, 
4.49400000e+04,   4.49700000e+04,   4.50000000e+04])

Unfortunately, chained comparisons aren't supported by numpy, so:

 >>> np.logical_and(0.0 <= x, x <= 15000.0)
array([ True,  True,  True, False, False, False])

Now for the indices:

 >>> np.arange(x.shape[0])
array([0, 1, 2, 3, 4, 5])

Extract the indices where the Boolean value is True:

 >>> np.extract(np.logical_and(0.0 <= x, x <= 15000.0), 
np.arange(x.shape[0]))
array([0, 1, 2])



More information about the Python-list mailing list