Finding the number of values ​​returned by numpy.where

I would like to find the number of places where numpy.where evaluates to true. The following solution works, but rather ugly.

b = np.where(a < 5) num = (b[0]).shape[0] 

I come from a language where I need to check if num> 0 before proceeding with something to do with the resulting array. Is there a more elegant way to get num or a more Pythonic solution than finding num?

(For those familiar with IDL, I am trying to reproduce its simple b = where(a lt 5, num) .)

+4
source share
3 answers
 In [1]: import numpy as np In [2]: arr = np.arange(10) In [3]: np.count_nonzero(arr < 5) Out[3]: 5 

or

 In [4]: np.sum(arr < 5) Out[4]: 5 

If you still need to define b = np.where(arr < 5)[0] , use len(b) or b.size ( len() seems a little faster, but they are almost the same in terms of performance).

+6
source

This only works if the condition of the where statement means that the result is not evaluated False. But then it’s easy:

 import numpy as np a = np.random.randint(1,11,100) a_5 = a[np.where(a>5)] a_10 = a[np.where(a>10)] a_5.any() #True a_10.any() #False 

So, if you want, you can try this before assigning, of course:

 a[np.where(a>5)].any() #True a[np.where(a>10)].any() #False 
0
source

Another way

 In [14]: a = np.arange(100) In [15]: np.where(a > 1000)[0].size > 0 Out[15]: False In [16]: np.where(a > 10)[0].size > 0 Out[16]: True 
0
source

Source: https://habr.com/ru/post/1468827/


All Articles