Here is a vectorized way to get what you want.
Taking a
from your example:
a[(a < 0.2).any(axis=1).any(axis=1)] = 0.2
print(a)
gives:
array([[[ 0.2 , 0.2 , 0.2 ],
[ 0.2 , 0.2 , 0.2 ],
[ 0.2 , 0.2 , 0.2 ]],
[[ 0.28983508, 0.31122743, 0.67818926],
[ 0.42720309, 0.24416101, 0.5469823 ],
[ 0.22894097, 0.76159389, 0.80416832]],
[[ 0.25661154, 0.64389696, 0.37555374],
[ 0.87871659, 0.27806621, 0.3486518 ],
[ 0.26388296, 0.8993144 , 0.7857116 ]]])
Explanation:
Taking another example where each step will be more clear:
a = np.array([[[0.51442898, 0.90447442, 0.45082496],
[0.59301203, 0.30025497, 0.43517362],
[0.28300437, 0.64143037, 0.73974422]],
[[0.228676 , 0.59093859, 0.14441217],
[0.37169639, 0.57230533, 0.81976775],
[0.95988687, 0.43372407, 0.77616701]],
[[0.03098771, 0.80023031, 0.89061113],
[0.86998351, 0.39619143, 0.16036088],
[0.24938437, 0.79131954, 0.38140462]]])
Let's see which elements are less than 0.2:
print(a < 0.2)
gives:
array([[[False, False, False],
[False, False, False],
[False, False, False]],
[[False, False, True],
[False, False, False],
[False, False, False]],
[[ True, False, False],
[False, False, True],
[False, False, False]]])
From here we would like to get indices of those 2D arrays that have at least one True
element: [False, True, True]
. We require np.any
for this. Note that I will be using np.ndarray.any
method chaining here instead of nesting function calls of np.any
. 1
Now just using (a < 0.2).any()
will give just True
because by default it performs logical OR over all dimensions. We have to specify axis
parameter. In our case we will be fine with either axis=1
or axis=2
.2
print((a < 0.2).any(axis=1))
gives3:
array([[False, False, False],
[False, False, True],
[ True, False, True]])
From here we get desired boolean indices by applying another .any()
along the rows:
print((a < 0.2).any(axis=1).any(axis=1))
gives:
array([False, True, True])
Fianlly, we can simply use this boolean index array to replace the values of the original array:
a[(a < 0.2).any(axis=1).any(axis=1)] = 0.2
print(a)
gives:
array([[[0.51442898, 0.90447442, 0.45082496],
[0.59301203, 0.30025497, 0.43517362],
[0.28300437, 0.64143037, 0.73974422]],
[[0.2 , 0.2 , 0.2 ],
[0.2 , 0.2 , 0.2 ],
[0.2 , 0.2 , 0.2 ]],
[[0.2 , 0.2 , 0.2 ],
[0.2 , 0.2 , 0.2 ],
[0.2 , 0.2 , 0.2 ]]])
1Just compare chaining:
a[(a < 0.2).any(axis=1).any(axis=1)] = 0.2
with nesting:
a[np.any(np.any(a < 0.2, axis=1), axis=1)] = 0.2
I think the latter is more confusing.
2For me this was difficult to comprehend at first. What helped me was to draw an image of a 3x3x3 cube, print results for different axis, and check which axis correspond to which directions. Also, here is an explanation of using axis with np.sum
in 3D case: Axis in numpy multidimensional array.
3One could expect to get [False, True, True]
at once which is not the case. For explanation see this: Small clarification needed on numpy.any for matrices