1

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]])
2
  • Not sure if learning Python via the use of numpy is the best path to follow (in a general case). Commented Aug 22, 2017 at 7:19
  • 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 Commented Jun 2, 2018 at 8:40

3 Answers 3

2

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]])

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.