Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Number of values within a specific range in Python

I have an array T. I am trying to find the number of values within a specified range through T1 but I am getting an error. I present the expected output.

T=np.array([4.7,5.1,2.9])
T1=np.flatnonzero(2<T<3,3<T<4,4<T<5)
print(T1)

The error is

in <module>
    T1=np.flatnonzero(2<T<3,3<T<4,4<T<5)

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

The expected output is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

T1=[1,0,1]

>Solution :

  • flatnonzero has nothing to do with what you want.
  • Furthermore, the error ‘The truth value of an array with more than one element is ambiguous’ comes from the double condition 2<T<3: you need to separate it into 2 conditions: (2<T) & (T<3).
  • T[(2<T) & (T<3)] will yield an array of the values of T respecting the conditions.

Thus, if you need to count the elements of T that are between 2 and 3, you can do:

len(T[(2 <T) & (T < 3)])

To obtain what you want, you could then do this:

Ranges = [(2,3),(3,4),(4,5)]
T1 = [len(T[(a < T) & (T < b)]) for a,b in Ranges]

print(T1)
# [1, 0, 1]

To print the actual values fitting the criteria, you can do:

T2 = [list(T[(a < T) & (T < b)]) for a,b in Ranges]

print(T2)
# [[2.9], [], [4.7]]

To get the corresponding indices, we finally have a use for flatnonzero:

T3 = [list(np.flatnonzero((a < T) & (T < b))) for a,b in Ranges]

print(T3)
# [[2], [], [0]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading