python - 替换满足特定阈值的python ndarray的值

标签 python python-2.7 numpy where-clause

我想将某个阈值内的巨大 python ndarray 的值替换为 0。比如在 [-0.1 和 0.1] 的阈值内。什么是最有效的方法?这是一个相当大的数组:

>>>np.shape(np_w)
shape=(1, 1, 1024, 1024) dtype=float32

我知道我们这里没有 Matlab 的 ismember,但是,搜索 numpy 文档,我找到了 np.in1dnp.isin .到目前为止,我的解决方案看起来并不好而且很慢:

import numpy as np
Threshhold=X

res=np.isin(np_w,np_w[(np_w>=-Threshhold) & (np_w<=Threshhold)])
indicesToReplace=np.where(res)
np_w[indicesToReplace]=0

最佳答案

如果是围绕0的对称区间你可以使用 abs<boolean array indexing (类似于 integer array indexing,但在这种情况下,您不需要条件周围的 np.where):

my_np[abs(my_np) <= treshhold] = 0

这将用 0 替换所有绝对值小于或等于阈值的值.

如果您需要更通用的解决方案,比如阈值下限的绝对值不等于阈值上限,那么您可以使用 & 组合表达式:

my_np[(my_np >= lower_treshhold) & (my_np <= upper_threshhold)] = 0

关于python - 替换满足特定阈值的python ndarray的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46333375/

相关文章:

python - 增加在 Python 中进行单元测试的类的日志记录详细程度

python - 对于排序数组来说,更快地替代 np.where

python - "python3 unattended upgrade shutdown"是什么进程?

python - 如何在不使用 PSUtil 的情况下获取 python 2.7 中的 CPU 使用率

python - 如何在Python中 reshape 列表中的多个数组

python - 上传从 cv2.imdecode() 返回的图像时遇到问题

python-3.x - 如何将 log(a-x) 类型的函数与 scipy.曲线拟合?

python - 有没有办法将 h2oframe 转换为 Pandas 数据帧

python - 字典的具体实现

python - 在 python 函数中使用 *args、**kwargs 时为 "got multiple values for keyword argument"