Python一种用不同的dtype(单元8和单元16)掩盖两个数组的方法

Gia*_*ear 2 python arrays optimization numpy

我有2个数组:

mask:值为0和1,dtype = uint8

>>> mask
array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [1, 1, 1, ..., 0, 0, 0],
       ..., 
       [1, 1, 1, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint8)
Run Code Online (Sandbox Code Playgroud)

和prova_clip

>>> prova_clip
array([[289, 281, 271, ..., 257, 255, 255],
       [290, 284, 268, ..., 260, 260, 259],
       [294, 283, 264, ..., 265, 263, 257],
       ..., 
       [360, 359, 360, ..., 335, 338, 331],
       [359, 364, 369, ..., 337, 342, 339],
       [358, 363, 368, ..., 332, 331, 332]], dtype=uint16)
Run Code Online (Sandbox Code Playgroud)

我希望使用代码保存方法来掩盖带掩码的prova_clip

array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [294, 283, 264, ..., 0, 0, 0],
       ..., 
       [360, 359, 360, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint16)
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 5

我错过了什么吗?这看起来很简单:

prova_clip*mask
Run Code Online (Sandbox Code Playgroud)

这是一个例子:

>>> a = np.arange(10,dtype=np.uint16)
>>> mask = np.ones(10,dtype=np.uint8)
>>> mask[1:3] = 0
>>> a*mask
array([0, 0, 0, 3, 4, 5, 6, 7, 8, 9], dtype=uint16)
Run Code Online (Sandbox Code Playgroud)

您也可以采用复杂的方式来修改数组.

>>> b = np.arange(10,dypte=np.uint16)
>>> b[~mask.astype(bool)] = 0
>>> b
array([0, 0, 0, 3, 4, 5, 6, 7, 8, 9], dtype=uint16)
Run Code Online (Sandbox Code Playgroud)

最后,有numpy.where:

>>> c = np.arange(10,dtype=np.uint8)
>>> np.where(mask==0,0,c)
array([0, 0, 0, 3, 4, 5, 6, 7, 8, 9], dtype=uint16)
Run Code Online (Sandbox Code Playgroud)