Apply Mask Array 2d to 3d

为君一笑 提交于 2021-01-27 05:07:26

问题


I want to apply a mask of 2 dimensions (an NxM array) to a 3 dimensional array (a KxNxM array). How can I do this?

2d = lat x lon

3d = time x lat x lon

import numpy as np

a = np.array(
    [[[ 0,  1,  2],
      [ 3,  4,  5],
      [ 6,  7,  8]],

     [[ 9, 10, 11],
      [12, 13, 14],
      [15, 16, 17]],

     [[18, 19, 20],
      [21, 22, 23],
      [24, 25, 26]]])

b = np.array(
    [[ 0, 1, 0],
     [ 1, 0, 1],
     [ 0, 1, 1]])

c = np.ma.array(a, mask=b)  # this behavior is wanted 

回答1:


There are quite a few different ways to choose from. What you want to do is align the mask (of lower dimension) to the array that has the extra dimension: the important part is that you get the number of elements in both arrays the same, as the first example shows:

np.ma.array(a, mask=np.concatenate((b,b,b)))  # shapes are (3, 3, 3) and (9, 3)
np.ma.array(a, mask=np.tile(b, (a.shape[0],1)))  # same as above, just more general as it doesn't require you to specify just how many times you need to stack b.
np.ma.array(a, mask=a*b[np.newaxis,:,:])  # used broadcasting


来源:https://stackoverflow.com/questions/29165820/apply-mask-array-2d-to-3d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!