在python中,如何替换数组中高于上限或低于下限的数字



我正在尝试从分布中随机生成数字。不在我要替换的平均值的两个标准偏差内的数字,这样最终数组中的所有数字都在这个范围内。这是我目前拥有的代码:

mean = 150
COV = 0.4
sd = COV*mean
upper_limit = mean + 2*sd
lower_limit = mean - 2*sd
capacity = np.random.normal(mean, sd, size = (1,96))
for x in capacity:
while x > upper_limit:
x = np.random.normal(mean, sd, size = 1)
while x < lower_limit:
x = np.random.normal(mean, sd, size = 1)

但是,我收到错误消息ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
有人能帮我解决这个问题吗?

不要遍历numpy数组来对数组的每个元素执行某些操作。使用numpy的全部目的是通过从不迭代来加快速度。

要检查capacity中大于upper_limit的所有值,只需执行以下操作:

capacity > upper_limit

然后,你可以通过这种方式获得这些项目的索引:

too_high_indices = np.where(capacity > upper_limit)

然后,您可以生成一个新的随机数组来分配给所有这些数组,例如

capacity[too_high_indices] = np.random.normal(mean, sd, size=len(too_high_indices))

最后,你这样做:

too_high_indices = np.where(capacity > upper_limit)
while np.any(too_high_indices):
capacity[too_high_indices] = np.random.normal(
mean, sd, size=len(too_high_indices))
too_high_indices = np.where(capacity > upper_limit)

然后重复下限。

这样,即使尺寸增长,它也会相对较快。

我认为应该将size参数从(1, 96)更改为96。因为这里的x的形状是(96,),所以它是一个数组,因此不能与单个浮点值相比较。

# print(capacity)
# changed = set([])
for i in range( len(capacity[0]) ):
while capacity[0][i] > upper_limit or capacity[0][i] < lower_limit:
capacity[0][i] = np.random.normal(mean, sd, size = 1)[0]
# changed.add(i)
# print(capacity)
# print(changed)

最新更新