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
-
2Did you read the official docs : docs.scipy.org/doc/numpy/reference/generated/numpy.where.html? Which specific part are you stuck with on its explanation?Divakar– Divakar2017年07月24日 11:02:14 +00:00Commented Jul 24, 2017 at 11:02
-
my question is how do we go output ndarray(1,3) in above examplevenkysmarty– venkysmarty2017年07月24日 11:25:22 +00:00Commented Jul 24, 2017 at 11:25
-
Possible duplicate of Apply function to masked numpy array. One more : stackoverflow.com/questions/35188508Divakar– Divakar2017年07月24日 11:32:55 +00:00Commented Jul 24, 2017 at 11:32
2 Answers 2
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]
Comments
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])