Reputation: 13
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.
Upvotes: 0
Views: 563
Reputation: 96
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.
Upvotes: 1