如何正确掩盖一个numpy的二维数组? [英] How to properly mask a numpy 2D array?
本文介绍了如何正确掩盖一个numpy的二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个二维坐标数组,看起来像
Say I have a two dimensional array of coordinates that looks something like
x = array([[1,2],[2,3],[3,4]])
到目前为止,在以前的工作中,我生成了一个面具,最终看起来像
Previously in my work so far, I generated a mask that ends up looking something like
mask = [False,False,True]
当我尝试在2D坐标矢量上使用此蒙版时,出现错误
When I try to use this mask on the 2D coordinate vector, I get an error
newX = np.ma.compressed(np.ma.masked_array(x,mask))
>>>numpy.ma.core.MaskError: Mask and data not compatible: data size
is 6, mask size is 3.`
我想这很有道理.因此,我尝试仅使用以下蒙版:
which makes sense, I suppose. So I tried to simply use the following mask instead:
mask2 = np.column_stack((mask,mask))
newX = np.ma.compressed(np.ma.masked_array(x,mask2))
我得到的是接近的东西:
And what I get is close:
>>>array([1,2,2,3])
达到我的期望(和想要):
to what I would expect (and want):
>>>array([[1,2],[2,3]])
必须有一种更简单的方法吗?
There must be an easier way to do this?
推荐答案
这是您要寻找的吗?
import numpy as np
x[~np.array(mask)]
# array([[1, 2],
# [2, 3]])
或者从 numpy屏蔽数组:
newX = np.ma.array(x, mask = np.column_stack((mask, mask)))
newX
# masked_array(data =
# [[1 2]
# [2 3]
# [-- --]],
# mask =
# [[False False]
# [False False]
# [ True True]],
# fill_value = 999999)
这篇关于如何正确掩盖一个numpy的二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文