需要花点功夫来查找,但是这里是 threshold
的代码(scipy/stats/mstats_basic.py
):
def threshold(a, threshmin=None, threshmax=None, newval=0):
a = ma.array(a, copy=True)
mask = np.zeros(a.shape, dtype=bool)
if threshmin is not None:
mask |= (a < threshmin).filled(False)
if threshmax is not None:
mask |= (a > threshmax).filled(False)
a[mask] = newval
return a
In [152]: a = np.array([9, 9, 6, 3, 1, 6, 1, 0, 0, 8])
In [153]: stats.threshold(a, threshmin=2, threshmax=8, newval=-1)
/usr/local/bin/ipython3:1: DeprecationWarning: `threshold` is deprecated!
stats.threshold is deprecated in scipy 0.17.0
#!/usr/bin/python3
Out[153]: array([-1, -1, 6, 3, -1, 6, -1, -1, -1, 8])
In [154]: np.clip(a,2,8)
Out[154]: array([8, 8, 6, 3, 2, 6, 2, 2, 2, 8])
....
将剪裁尽量减少或最大化是有意义的;另一方面,阈值将所有超出范围的值转换为其他值,例如0或-1。听起来并不那么有用。但实现起来并不难:
In [156]: mask = (a<2)|(a>8)
In [157]: mask
Out[157]: array([ True, True, False, False, True, False, True, True, True, False], dtype=bool)
In [158]: a1 = a.copy()
In [159]: a1[mask] = -1
In [160]: a1
Out[160]: array([-1, -1, 6, 3, -1, 6, -1, -1, -1, 8])
本质上来说,这和我引用的代码是一样的,只是在处理最小值或最大值的None
情况方面有所不同。
threshold
的直接替代品。 - user15964就算价值不高,np.clip如果使用得当,可以直接替代threshold:
np.clip(array-threshold,0,1)
numpy.clip()
- 这是scipy
列表 上的对话。 - AChampiona
,那么a[a < cutoff] = 0
将会把所有小于cutoff
的元素都变成零。 - σηγ