Number of values within a certain range in Python

Question:

I have an array A. I want to print total number of values in the range [1e-11,1e-7]. But I am getting an error. I present the expected output.

import numpy as np 

A=np.array([ 4.21922009e+002,  4.02356746e+002,  3.96553289e-09,
        3.91811967e-010,  3.88467908e-08,  3.86636300e-010])

B=1e-11<A<1e-07
print(B)

The error is

 in <module>
    B=1e-11<A<1e-07

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The expected output is

4
Asked By: AEinstein

||

Answers:

You can’t use your code with numpy array:

B = sum((1e-11<A) & (A<1e-07))
print(B)

# Output
4

It doesn’t make sense for Python (and not numpy) to compare 2 scalar values to an array.

Answered By: Corralien

The numpy-way is to refactor the interval condition into two subconditions using the & operator:

a = np.array([ 4.21922009e+002,  4.02356746e+002,  3.96553289e-09,
        3.91811967e-010,  3.88467908e-08,  3.86636300e-010])

mask = (1e-11<a) & (a<1e-07)

# if you care about the values of the filtered array
print(a[mask].size)

# or just
print(np.count_nonzero(mask))
Answered By: cards
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.