24

我想从列表中替换大纲。因此我定义了一个上限和下限。现在,上面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)
4

2 回答 2

36

您可以使用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])
于 2016-12-26T10:20:30.010 回答
14

对于不依赖的替代方案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!),您将遇到以下三种情况之一:

  1. x < lower_bound
  2. x > upper_bound
  3. lower_bound <= x <= upper_bound.

在情况 1 中,max/min表达式首先计算为max(lower_bound, x),然后解析为lower_bound

在情况 2 中,表达式首先变为max(lower_bound, upper_bound),然后变为upper_bound

在案例 3 中,我们得到max(lower_bound, x)which 解析为 just x

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

于 2016-12-26T15:24:56.267 回答