【问题标题】:How can I replace numbers in an array that fall above an upper bound or below a lower bound in python?python - 如何替换数组中高于上限或低于python下限的数字?
【发布时间】:2021-04-13 11:14:55
【问题描述】:

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

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()
谁能帮忙解决这个问题?

【问题讨论】:

标签: python numpy


【解决方案1】:

不要遍历 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)

然后重复下限。

这样,即使尺寸变大,也会比较快。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 验证我的答案,然后请 :) 很高兴它有帮助
    • 我刚刚意识到,虽然更改大小允许代码运行,但它并没有替换两个标准差之外的任何值
    【解决方案3】:
    # 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)
    

    【讨论】:

      猜你喜欢
      • 2019-02-18
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      相关资源
      最近更新 更多