0

I am new to python and numpy. I have written code to teach myself. However, I cannot comprehend how the below code produces its result.

Input

np.where([[True, False], [True, True]], 
         [[1, 2], [3, 4]], [[9, 8], [7, 6]])

Output

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

I do not understand how this result is achieved.

3
  • You apply np.where in a list that contains 3 sublists. Are you sure this is what you need? Commented Aug 2, 2019 at 16:58
  • help(np.where) will explain that this takes elements from x ([[1,2],[3,4]) where condition is True, and elements from y elsewhere, in this case, the False condition is returning the 8 value from y. Commented Aug 2, 2019 at 16:58
  • 1
    this is literally the example from the help dox. Commented Aug 2, 2019 at 17:01

1 Answer 1

1

What you are seeing is a combination of broadcasting and the function of the where conditional. In the numpy.where docstring it states:

Parameters: condition : array_like, bool Where True, yield x, otherwise yield y.

In your case your boolean input is (2, 2), and is followed by two arrays of shape (2, 2).

It applies:

[True False] 
[True True ]

to x:

[1, 8]
[3, 4]

resulting in:

[1, _]
[3, 4]

and since the second element is false takes from the second input y:

[9, 8]
[7, 6]

resulting in:

[_, 8]
[_, _]

Then combines to get the output you see.

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

1 Comment

Thank you. I had read the documentation. Like David Zemens the example is from there I just could not understand the logic behind this specific example. Your explanation. Cleared it up.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.