Say I have a multi-dimensional array, for example:
a = array([[[86, 27],
[26, 59]],
[[ 1, 16],
[46, 5]],
[[71, 85],
[ 6, 71]]])
And say I have a one-dimensional array (b
), with some values which may be seen in my multi-dimensional array (a
):
b = [26, 16, 6, 71]
Now I want to replace all of the non-intersecting values in array a
with zero. I want to get the following result:
a = array([[[0, 0],
[26, 0]],
[[ 0, 16],
[ 0, 0]],
[[71, 0],
[ 6, 71]]])
How could I achieve this?
I tried several ways of coding which didn't work. I expected the following line to work, but I think there is an issue with using not in
in this format:
a = np.where(a not in b, int(0), a)
I get the following error when I try this:
arr = np.where(arr not in required_intensities, int(0), arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I am unsure what to try next. Any ideas?
CodePudding user response:
np.isin()
is perfect for this:
a[~np.isin(a, b)] = 0
Output:
>>> a
array([[[ 0, 0],
[26, 0]],
[[ 0, 16],
[ 0, 0]],
[[71, 0],
[ 6, 71]]])