Say I have a multi-dimensional array, for example:
JavaScript
x
9
1
a = array([[[86, 27],
2
[26, 59]],
3
4
[[ 1, 16],
5
[46, 5]],
6
7
[[71, 85],
8
[ 6, 71]]])
9
And say I have a one-dimensional array (b
), with some values which may be seen in my multi-dimensional array (a
):
JavaScript
1
2
1
b = [26, 16, 6, 71]
2
Now I want to replace all of the non-intersecting values in array a
with zero. I want to get the following result:
JavaScript
1
9
1
a = array([[[0, 0],
2
[26, 0]],
3
4
[[ 0, 16],
5
[ 0, 0]],
6
7
[[71, 0],
8
[ 6, 71]]])
9
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:
JavaScript
1
2
1
a = np.where(a not in b, int(0), a)
2
I get the following error when I try this:
JavaScript
1
3
1
arr = np.where(arr not in required_intensities, int(0), arr)
2
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
3
I am unsure what to try next. Any ideas?
Advertisement
Answer
np.isin()
is perfect for this:
JavaScript
1
2
1
a[~np.isin(a, b)] = 0
2
Output:
JavaScript
1
10
10
1
>>> a
2
array([[[ 0, 0],
3
[26, 0]],
4
5
[[ 0, 16],
6
[ 0, 0]],
7
8
[[71, 0],
9
[ 6, 71]]])
10