在遮罩数组中使用numpy数组时尺寸丢失

时间:2020-09-23 07:58:21

标签: python numpy

我有一个Masked数组和一个包含3维值的Numpy布尔数组。但是,当我在蒙版数组中使用numpy数组的索引时,会导致尺寸丢失。我不知道原因:

Masked_array = [[[--, 1, --],
                 [--, 1, --],
                 [--, 1, --]]]

运行此行给了我

masked_array = masked_array.mask
mm = ~np.logical_and.accumulate(masked_array)
list(masked_array[mm])

输出为[1, 1, 1] 代替[[1] [1] [1]] 我无法理解该错误,并尝试了各种方法。 您能帮我澄清一下疑问吗?谢谢

1 个答案:

答案 0 :(得分:1)

在使用具有相同形状的蒙版对2D数组进行索引时,会得到一个1D数组:

a = np.random.random((4,4))
a[np.random.choice([True,False], (4,4))].shape
# (7,)

不保留原始形状,因为布尔索引的结果是您可能会得到一个锯齿状的数组,numpy不支持该数组。因此,默认情况下,就像上面的示例一样,它只会为您拉平结果。

如果您知道自己将因此为一列编制索引,并且想要保留2D形状,则可以随时添加新轴:

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

masked_array = np.ma.masked_array(a, a==0)

mask = masked_array.mask
mm = ~np.logical_and.accumulate(mask)

masked_array[mm,None].data
array([[1],
       [1],
       [1]])

尽管如上所述,您总是会得到一个受挤压的阵列,必须根据需要对其进行重塑。