numpy.all has where parameter for what purpose

Viewed 42

There is this where parameter in np.all and I am not sure what it is for?

The documentation did not help much here.

Any nice explanation somewhere? or can anyone explain it?

1 Answers

From the documentation:

where array_like of bool, optional Elements to include in checking for all True values. See reduce for details.

It basically tells which elements to consider for the application of the function. For example:

import numpy as np

arr = np.arange(5)
print(np.all(arr % 2 == 0))
print(np.all(arr % 2 == 0, where=[False, False, True, False, False]))

Output

False
True

In this expression:

np.all(arr % 2 == 0, where=[False, False, True, False, False])

Only the element at index 2 (that coincidentally is also 2) is considered. If you change to:

np.all(arr % 2 == 0, where=[False, False, True, True, False])
# False

the output is False because it will use the elements at index 2 and 3 (2 and 3 respectively).

Additional information and examples are found in the documentation of reduce, quote (emphasis mine):

where array_like of bool, optional A boolean array which is broadcasted to match the dimensions of array, and selects elements to include in the reduction. Note that for ufuncs like minimum that do not have an identity defined, one has to pass in also initial.

Related