<p>您可以考虑使用<a href="http://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html" rel="noreferrer">^{<cd1>}</a>来表示满足条件的元素子集:</p>
<pre><code>import numpy as np
arr = np.asarray([[[[1, 11], [2, 22], [3, 33]],
[[4, 44], [5, 55], [6, 66]]],
[[[7, 77], [8, 88], [9, 99]],
[[0, 32], [1, 33], [2, 34]]]])
masked_arr = np.ma.masked_less(arr, 3)
print(masked_arr)
# [[[[-- 11]
# [-- 22]
# [3 33]]
# [[4 44]
# [5 55]
# [6 66]]]
# [[[7 77]
# [8 88]
# [9 99]]
# [[-- 32]
# [-- 33]
# [-- 34]]]]
</code></pre>
<p>如您所见,遮罩阵列保留其原始尺寸。您可以分别通过<code>.data</code>和<code>.mask</code>属性访问底层数据和掩码。大多数numpy函数不会考虑屏蔽值,例如:</p>
<pre><code># mean of whole array
print(arr.mean())
# 26.75
# mean of non-masked elements only
print(masked_arr.mean())
# 33.4736842105
</code></pre>
<p>对屏蔽数组和非屏蔽数组执行按元素操作的结果也将保留屏蔽的值:</p>
<pre><code>masked_arrsum = masked_arr + np.random.randn(*arr.shape)
print(masked_arrsum)
# [[[[-- 11.359989067421582]
# [-- 23.249092437269162]
# [3.326111354088174 32.679132708120726]]
# [[4.289134334263137 43.38559221094378]
# [6.028063054523145 53.5043991898567]
# [7.44695154979811 65.56890530368757]]]
# [[[8.45692625294376 77.36860675985407]
# [5.915835159196378 87.28574554110307]
# [8.251106168209688 98.7621940026713]]
# [[-- 33.24398289945855]
# [-- 33.411941757624284]
# [-- 34.964817895873715]]]]
</code></pre>
<p>总和仅在<code>masked_arr</code>的非屏蔽值上计算-您可以通过查看<code>masked_sum.data</code>来看到这一点:</p>
<pre><code>print(masked_sum.data)
# [[[[ 1. 11.35998907]
# [ 2. 23.24909244]
# [ 3.32611135 32.67913271]]
# [[ 4.28913433 43.38559221]
# [ 6.02806305 53.50439919]
# [ 7.44695155 65.5689053 ]]]
# [[[ 8.45692625 77.36860676]
# [ 5.91583516 87.28574554]
# [ 8.25110617 98.762194 ]]
# [[ 0. 33.2439829 ]
# [ 1. 33.41194176]
# [ 2. 34.9648179 ]]]]
</code></pre>