0

I hope that somebody can provide some clarification on how the numpy.where() function works. After trying out several different inputs, I cannot wrap my head around it. Taking the first example below, the output of:

np.where([True,False],[1,0],[3,4])

is:

array([1, 4])

How exactly is the array of Boolean values being applied to the arrays [1,0] and [3,4] to yield the output?

Results of some additional testing are shown below:

import numpy as np

np.where([True,False],[1,0],[3,4])
Out[129]: array([1, 4])

np.where([True,False],[1,0],[6,4])
Out[130]: array([1, 4])

np.where([True,False],[1,0],[0,0])
Out[131]: array([1, 0])

np.where([True,False],[0,0],[0,0])
Out[132]: array([0, 0])

np.where([True,False],[1,0],[0,12])
Out[133]: array([ 1, 12])

np.where([True,False],[1,6],[4,12])
Out[134]: array([ 1, 12])

np.where([True,True],[1,6],[4,12])
Out[135]: array([1, 6])

np.where([False,False],[1,6],[4,12])
Out[136]: array([ 4, 12])

np.where([True,False],[1,0],[3,4])
Out[137]: array([1, 4])

np.where([True,True],[1,0],[3,4])
Out[138]: array([1, 0])

np.where([True,True],[1,0],[3,4])
Out[139]: array([1, 0])

np.where([True,False],[1,0],[3,4])
Out[140]: array([1, 4])
0

1 Answer 1

1

In case you give 3 arguments to np.where the first argument is the condition that decides if the corresponding value in the result is taken from the second argument (if the value in the condition is True) or from the third argument (if the value in the condition is False).

So when all values are True it will be a copy of the first argument, and if all values are False it will be a copy of the second argument. In case they are mixed it will be a combination.

Think of it as a more sophisticated version of:

def where(condition, x, y):
    result = []
    for idx in range(len(condition)):
        if condition[idx] == True:
            result.append(x[idx])
        else:
            result.append(y[idx])
    return result

That function is of course much slower (not even the fastest pure Python equivalent), it also doesn't support broadcasting or multidimensional arrays and the one-argument form but I hope it helps in understanding the 3 argument form of np.where.

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

1 Comment

Thank you very much. That is exactly addressed my confusion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.