python - 聚合 numpy 屏蔽数组

标签 python numpy

我正在与 numpy masked arrays 合作并且有一个微不足道的操作我无法弄清楚如何以简单的方式完成它。如果我有两个屏蔽数组,如何将它们聚合到另一个仅包含未屏蔽值的数组中?

In [1]: import numpy as np

In [2]: np.ma.array([1, 2, 3], mask = [0,1,1])
Out[2]:
masked_array(data = [1 -- --],
             mask = [False  True  True],
       fill_value = 999999)

In [3]: np.ma.array([4, 5, 6], mask = [1,1,0])
Out[3]:
masked_array(data = [-- -- 6],
             mask = [ True  True False],
       fill_value = 999999)

如果我想得到:

masked_array(data = [1 -- 6],
             mask = [False  True False],
       fill_value = 999999)

最佳答案

使用 numpy.dstack 堆叠掩码和数组并创建一个新的屏蔽数组,然后您可以使用 numpy.prod 获得所需的输出:

>>> a1 = np.ma.array([1, 2, 3], mask = [0,1,1])
>>> a2 = np.ma.array([7, 8, 9], mask = [1,1,0])
>>> arr = np.ma.array(np.dstack((a1, a2)), mask=np.dstack((a1.mask, a2.mask)))
>>> np.prod(arr[0], axis=1)
masked_array(data = [1 -- 9],
             mask = [False  True False],
       fill_value = 999999)

关于python - 聚合 numpy 屏蔽数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28407265/

相关文章:

python - 如何加速将tensorflow_datasets中的张量转换为numpy数组的代码?

Python:类型和数据类型之间的混淆

python - 从 pandas 单元格内的列表中删除括号

python - 用一组点求解方程

python - Python 列表中第一次出现零的索引

python - 如何识别 Bootstrap 模板中的 CSS 样式路径?

python - 提高 Numpy 性能

Python 类型错误 : only integer scalar arrays can be converted to a scalar index

python - 枕头 PixelAccess 类型错误 : function takes exactly 1 argument (4 given)

python - Flask-WTF : CSRF token missing