[英]How can one apply a mask on a numpy array which leaves the original values unchanged if the mask's value is True and sets it to zero if False?
I have a 3D numpy array:我有一个 3D numpy 数组:
image = np.random.random((2, 2, 3))
[[[0.01188816 0.46263957 0.00943777]
[0.0742566 0.8375209 0.259363 ]]
[[0.30823133 0.17924745 0.74292469]
[0.68490255 0.03143513 0.68233715]]]
and a mask:和一个面具:
[[[ True True True]
[False False False]]
[[False False False]
[False False False]]]
desired output:所需的输出:
[[[0.01188816 0.46263957 0.00943777]
[0 0. 0. ]]
[[0. 0. 0. ]
[0. 0. 0. ]]]
So, the original array should be modified according to the mask - if the mask's value is False, the entry should be set to 0, otherwise left unchanged.所以,应该根据掩码修改原始数组——如果掩码的值为False,则该条目应设置为0,否则保持不变。
What I tried:我尝试了什么:
(image[unknown_array])
[0.01188816 0.46263957 0.00943777]
This indeed gives the right values, but without the zeros.这确实给出了正确的值,但没有零。 How can I get the zeros to the right place?我怎样才能把零放在正确的地方?
Thank you very much for any help.非常感谢您的帮助。
You can do it using different ways:您可以使用不同的方式来做到这一点:
x = np.arange(1,7).reshape(2,3) # numbers from 1 to 6
mask = x % 2 == 0 # mask for even numbers
print(x, mask)
# (array([[1, 2, 3],
# [4, 5, 6]]),
# array([[False, True, False],
# [ True, False, True]]))
Szczesny suggestion is perhaps the simplest one: Szczesny的建议可能是最简单的一个:
y = x * mask
print(y)
# array([[0, 2, 0],
# [4, 0, 6]])
Filling the y
array "by hand": “手动”填充y
数组:
y = np.zeros_like(x)
y[mask] = x[mask]
print(y)
# array([[0, 2, 0],
# [4, 0, 6]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.