python - 应用蒙版阵列 2d 到 3d

标签 python arrays python-2.7 numpy

我想将 2 维(NxM 数组)的掩码应用于 3 维数组(KxNxM 数组)。我该怎么做?

2d = 纬度 x 经度

3d = 时间 x 纬度 x 经度

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 

最佳答案

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

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

关于python - 应用蒙版阵列 2d 到 3d,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29165820/

相关文章:

javascript - 使用 Reduce 方法在 JavaScript 中反转字符串

c - 如何在C中检测未初始化的字符串

python - 有条件地将 pandas 数据框中的值替换为计算值

python - 值错误 : axes don't match array when loading previously saved model

Python 多重深度复制行为

java - 数组的数组列表或操作系统有更好的方法吗?

python - "Map"Python 中的嵌套列表

python - 如何调整使用 Pandas 创建的条形图的底部

python - 在OSX Yosemite上为Python 2.7安装OpenCV时出错-错误:无匹配功能

python - 如何映射到 Pandas 列表列中的值