查看np.percentile 代码,很明显它对掩码数组没有什么特别之处。
def percentile(a, q, axis=None, out=None,
overwrite_input=False, interpolation='linear', keepdims=False):
q = array(q, dtype=np.float64, copy=True)
r, k = _ureduce(a, func=_percentile, q=q, axis=axis, out=out,
overwrite_input=overwrite_input,
interpolation=interpolation)
if keepdims:
if q.ndim == 0:
return r.reshape(k)
else:
return r.reshape([len(q)] + k)
else:
return r
其中_ureduce 和_percentile 是在numpy/lib/function_base.py 中定义的内部函数。所以真正的动作比较复杂。
掩码数组有两种使用 numpy 函数的策略。一种是fill - 用无害的值替换掩码值,例如求和时为 0,求积时为 1。另一种是compress数据——即删除所有被屏蔽的值。
例如:
In [997]: data=np.arange(-5,10)
In [998]: mdata=np.ma.masked_where(data<0,data)
In [1001]: np.ma.filled(mdata,0)
Out[1001]: array([0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [1002]: np.ma.filled(mdata,1)
Out[1002]: array([1, 1, 1, 1, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [1008]: mdata.compressed()
Out[1008]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
哪个会给你想要的percentile?填充还是压缩?或者没有。您需要充分了解百分位数的概念,才能知道它应该如何应用于您的掩码值。