0

I am reading about vectorized expressions in cheat sheet. It is mentioned as below

Vectorized expressions

np.where(cond, x, y) is a vectorized version of the expression ‘x if condition else y’

example:

np.where([True, False], [1, 2], [2, 3]) => ndarray (1, 3)

I am not able understand above example. My understanding is that we should have expression but here we have list of [True, False].

Request to explain in break up and how we got output of ndarray(1,3)

Thanks

3

2 Answers 2

3

I normally use np.where to convert a boolean array to an index array. Consider this example:

In [12]: a = np.random.rand((10))

In [13]: a
Out[13]: 
array([ 0.80785098,  0.49922039,  0.02018482,  0.69514821,  0.87127179,
        0.23235574,  0.73199572,  0.79935066,  0.46667908,  0.11330817])

In [14]: bool_array = a > 0.5

In [15]: bool_array
Out[15]: array([ True, False, False,  True,  True, False,  True,  True, False, False], dtype=bool)

In [16]: np.where(bool_array)
Out[16]: (array([0, 3, 4, 6, 7]),)

Explanation of your example. For every value in cond: if True, pick value from x, otherwise pick value from y.

cond: [True, False]
x   : [1, 2]
y   : [2, 3]

Result:
cond[0] == True  -> out[0] == x[0]
cond[1] == False -> out[1] == y[1]
out == [1, 3]
Sign up to request clarification or add additional context in comments.

Comments

0

The array [True, False] is what would be produced by an expression like x<y where x=np.array([1,1]) and y=np.array([2,0]). So cond is a boolean array that is often the result of an expression like the previous one. An example of a more real-world-ish usage would therfore be :

np.where(x<y, [1, 2], [2, 3])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.