将Mask Array 2d应用于3d

mar*_*ues 4 python arrays numpy python-2.7

我想将2维掩模(NxM数组)应用于3维数组(KxNxM数组).我怎样才能做到这一点?

2d = lat x lon

3d =时间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 
Run Code Online (Sandbox Code Playgroud)

Oli*_* W. 9

有很多不同的方法可供选择.你想要做的是将掩码(较低维度)与具有额外维度的数组对齐:重要的是你得到两个数组中元素的数量相同,如第一个例子所示:

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
Run Code Online (Sandbox Code Playgroud)