arr = np.random.randint(0, 300, (500,500))
# 创建一个 500x500, 范围在 0 到 300 之间的 numpy 数组
使用 timeit 测试语句执行时间, 对多行则使用 %%timeit
1. 使用 python 内置索引
arr[arr > 255] = 255
2. np.minimum(), np.maximum() 和 np.clip()
对大于 255 的替换成 255
result = np.minimum(arr, 255)
对小于 0 的替换成 0
result = np.maximum(arr, 0)
如果不创建新的数组 result, 只做 in-place 修改, 则使用参数 out:
np.minimum(arr, 255, out=arr)
对于上限和/或下限
result = np.clip(arr, 0, 255)
同样有 in-place
np.clip(arr, 0, 255, arr)
注意: in-place 的修改要更慢一些
3. np.where()
对大于 255 的使用 255 替换
np.where(nums > 255, 255, nums)
该方法速度更快
4. np.putmask()
np.putmask(arr, arr > 255, 255)
concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending 错误 -- Python
- 17726 views