用上限和下限(钳位、剪裁、阈值)替换列表值的 Pythonic 方法?

标签 python arrays numpy clip clamp

我想替换列表中的大纲。因此我定义了一个上限和下限。现在,upper_boundlower_bound 之下的每个值都替换为绑定(bind)值。我的方法是使用 numpy 数组分两步执行此操作。

现在我想知道是否可以一步完成,因为我想它可以提高性能和可读性。

有没有更短的方法可以做到这一点?

import numpy as np

lowerBound, upperBound = 3, 7

arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

arr[arr > upperBound] = upperBound
arr[arr < lowerBound] = lowerBound

# [3 3 3 3 4 5 6 7 7 7]
print(arr)

最佳答案

你可以使用numpy.clip:

In [1]: import numpy as np

In [2]: arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [3]: lowerBound, upperBound = 3, 7

In [4]: np.clip(arr, lowerBound, upperBound, out=arr)
Out[4]: array([3, 3, 3, 3, 4, 5, 6, 7, 7, 7])

In [5]: arr
Out[5]: array([3, 3, 3, 3, 4, 5, 6, 7, 7, 7])

关于用上限和下限(钳位、剪裁、阈值)替换列表值的 Pythonic 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41329691/

相关文章:

python - 为什么ndarray显示为黑色图像?

python - LinAlg错误: SVD did not converge in matplotlib PCA

python - 使用 savez 命名 numpys 关键字,同时使用任意数量的参数

python - Spyder 5 缺少依赖项 - spyder_kernels 版本错误

python - 从 Python 3.7 conda 环境中在 Spyder 下导入 numpy 时出现 ImportError

java - 使用java中的数组从文本文件中读取关键字

javascript - 如何从 div 数组中获取下一个对象?

python - Kubernetes Python驱逐API提示 'Name parameter required.'

python - 在 Windows 操作系统中的文件夹上设置 "hide"属性?

Java 老虎机类