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
T1=[1,0,1]
>Solution :
flatnonzerohas 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]]