我想为2D或1D蒙版数组提供有效的代码以从中提取1D数组。在2D情况下,一列将完全被遮盖,应将其删除(例如,可以按照此问题所示进行操作)。
import numpy as np
a = np.ma.masked_array(range(10*2), mask=[True, False]*10).reshape(10,2)
a = np.ma.masked_equal(a, 13)
b = np.ma.masked_equal(np.array(range(10)), 3)
print(a)
print(b)
# [[-- 1]
# [-- 3]
# [-- 5]
# [-- 7]
# [-- 9]
# [-- 11]
# [-- --]
# [-- 15]
# [-- 17]
# [-- 19]]
# [0 1 2 -- 4 5 6 7 8 9]
# HERE I would like the same indexing valid for both (2D and 1D) situations:
a = a[:, ~np.all(a.mask, axis=0)].squeeze()
b = b[:] # I am not supposed to know that b is actually 1D and not a problematic 2D array
print(a)
print(b)
# [1 3 5 7 9 11 -- 15 17 19]
# [0 1 2 -- 4 5 6 7 8 9]
print(a-b)
# [1 2 3 -- 5 6 -- 8 9 10]
实现此目的的有效pythonic代码是什么?
子问题:令我惊讶的是,在我尝试期间,以下各项确实奏效:
b = b[:, ~np.all(b.mask, axis=0)].squeeze()
print(b)
# [1 3 5 7 9 11 -- 15 17 19]
IndexError: too many indices for array
在此1D数组使用2D索引时,为什么没有出现错误?
有什么更好的选择来解决原始问题?谢谢!
a = a[:, ~np.all(a.mask, axis=0)].squeeze()
两种情况(一维和二维)都可以使用。
在你的榜样的1D情况下,你b[:, ~np.all(b.mask, axis=0)]
这是b[:, True]
。看来这应该引发索引错误,但在这种情况下的True
行为类似np.newaxis
,即的结果b[:, True]
是shape的数组(10,1)
。请参阅此SO答案,以了解其原因以及其背后的动机是什么(答案与0维情况有关,但事实证明,它适用于较大的尺寸)。squeeze
然后删除此额外的维度,以便您不会注意到它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句