It is often useful to access and modify only parts of an array, depending on its value. For instance, you might want to access all the positive elements of an array. This turns out to be possible using Boolean arrays, which act like masks to select only some elements of an array. The result of such indexing is always a vector. For instance, consider the following example:
B = array([[True, False], [False, True]]) M = array([[2, 3], [1, 4]]) M[B] # array([2,4]), a vector
In fact, the command M[B] is equivalent to M[B].flatten(). You can then replace the resulting vector with another vector. For instance, you can replace all the elements with zero:
M[B] = 0 M # [[0, 3], [1, 0]]
Or you can replace all the selected values with others:
M[B] = 10, 20 M # [[10, 3], [1, 20]]
By combining the creation of Boolean arrays (M > 2), smart indexing (indexing with a Boolean array), and broadcasting, you can...