Home > other >  Number of values within a certain range in Python
Number of values within a certain range in Python

Time:01-27

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

CodePudding user response:

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.

CodePudding user response:

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))
  • Related