As the title says, I'm trying to change the values of a circle in a 2D array if they fulfill a certain condition. So far I've got this from a different question on here:
import numpy as np
x = np.arange(0, 20)
y = np.arange(0, 20)
arr = np.zeros((y.size, x.size))
cx = 10.
cy = 10.
r = 4.
mask = (x[np.newaxis, :] - cx) ** 2 (y[:, np.newaxis] - cy) ** 2 < r ** 2
arr[mask] = 1
cx
and cy
are the coordinates of the circle's center, r
is its radius. mask
contains the circle, and all of the elements in it are set to 1, which works fine. What I want to do is only change their value only if they are less than 5 or whatever some similar condition. Obviously this array only has 0s, but my real data would have other values set beforehand).
CodePudding user response:
Masks are booleans, and you can combine them with other masks using bitwise operations or logical operations:
circle_mask = (x[np.newaxis, :] - cx) ** 2 (y[:, np.newaxis] - cy) ** 2 < r ** 2
less_than_5_mask = arr < 5
arr[circle_mask & less_than_5_mask] = 1
In this case, &
is the bitwise, elementwise boolean AND operator. If you wanted to replace locations that were in the circle and/or less than 5, you could use the |
operator instead.
&
is a faster eqivalent to np.bitwise_and
in this case. Since your arrays are boolean, you can use np.logical_and
to the same effect. Note that that is not the same as using the and
operator, since the operator will attempt to distill the entire array into a single boolean value, causing an error.