Arturo Diaz Renteria
Arturo Diaz Renteria

Reputation: 13

Can somebody explain how numpy.where and True/False works?

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

Answers (1)

T. Welsh
T. Welsh

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

Related Questions