1
votes

Trying to teach myself some python and I am super confused from the docs what the where function does. Can somebody explain the example from the documentation below step by step please?

>>> np.where([[True, False], [True, True]],
...          [[1, 2], [3, 4]],
...          [[9, 8], [7, 6]])
array([[1, 8],
       [3, 4]])
3
Not sure if learning Python via the use of numpy is the best path to follow (in a general case). - Ignacio Vergara Kausel
This actually got me confused as I thought the entire first condition must be met. So if you don't make the conditions in the same structure..automatic broadcast takes into place, some of them somewhat odd - dia

3 Answers

2
votes

The basic syntax is np.where(x, a, b) Wherever x is true, take that element of a, and wherever it's false, take an element of b. It's equivalent to something like this:

x = . . [[1, 0], [1, 1]]), not x =[[0, 1], [0, 0 ]]

array([[1, 2], [3, 4]]) + array([[7, 8], [9, 10]])

array([[1, 0], [3, 4]]) + array([[0, 8], [0, 0 ]]) = array([[1, 8], [3, 4]])

1
votes

Basically used as follows:

np.where(condition, value if condition is True, value if condition is False)

In this case:

condition is [[True, False], [True, True]]

value if condition is True is [[1, 2], [3, 4]].

value if condition is False is [[9, 8], [7, 6]].

The final result of array([[1, 8], [3, 4]]) is equal to the array from 'value if condition is True', except for the one location in condition where it is False. In this case, the value of 8 comes from the second array.

1
votes

I think it becomes pretty clear when you add linebreaks to arrange the inputs to look like matrices:

np.where( # First argument
         [[True, False], 
          [True, True]],
          # Second argument
          [[1, 2], 
           [3, 4]],
          # Third argument
          [[9, 8], 
           [7, 6]])

You can see the first argument as a mask that determines from which of the two following inputs elements should be taken.

The result

array([[1, 8],
       [3, 4]])

contains elements from the second argument wherever the mask is True and elements from the third argument where it is False.