用上下界替换列表值的python方法(夹紧、剪切、阈值化)?

2024-03-29 12:08:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从列表中替换大纲视图。因此我定义了一个上下界。现在,upper_bound上方和lower_bound下的每个值都将替换为绑定值。我的方法是使用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)

Tags: 方法numpy视图列表定义np数组upper
2条回答

您可以使用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])

对于不依赖numpy的替代方案,您可以一直这样做

arr = [max(lower_bound, min(x, upper_bound)) for x in arr]

如果您只想设置一个上限,当然可以写arr = [min(x, upper_bound) for x in arr]。或者类似地,如果您只需要一个下界,您可以使用max。在

这里,我已经应用了两个操作,一起编写。在

编辑:这里有一个稍微更深入的解释:

给定数组的元素x(假设你的upper_bound至少和你的lower_bound一样大!),您将有三种情况之一:

i)x < lower_bound

ii)x > upper_bound

iii)lower_bound <= x <= upper_bound。在

在case(i)中,max/min表达式首先计算为max(lower_bound, x),然后解析为lower_bound。在

在情况(ii)中,表达式首先变成max(lower_bound, upper_bound),然后变成{}。在

在案例(iii)中,我们得到max(lower_bound, x),它解析为x。在

在这三种情况下,输出都是我们想要的。在

相关问题 更多 >