gpt4 book ai didi

python - 将掩码结果转换为不同的随机数

转载 作者:太空宇宙 更新时间:2023-11-04 04:26:06 24 4
gpt4 key购买 nike

我想做这样的事情。

import numpy

# Create a 10x10 array of random numbers.
example_array = numpy.random.random_integers(0, 10, size=(10, 10))

# Locate values that equal 5 and turn them into a new random number.
example_array[example_array == 5] = numpy.random.random_integers(0, 10)

问题出在最后一行。它将单个随机数应用于所有屏蔽值,而不是每个值一个新的随机数。例如,如果选择数字 2,则所有 == 5 的值都变为 2。我希望每个值都有一个全新的值,而不是所有值都具有相同的随机值。我希望这是有道理的!请指教。

对于任何混淆,我们深表歉意。我还没有掌握 numpy 术语。

这是另一个可能有帮助的示例。

# Before replacing 5's with a random number.
array=[4, 5, 5,
5, 2, 3,
5, 4, 5]

# After replacing 5's with a random number.
array=[4, 1, 4,
7, 2, 3,
2, 4, 8]

这看起来应该很容易做,但我不知道如何有效地做。我想使用 mask 来提高速度。我目前的工作(而且 super 慢!)方法是遍历数组并为任何需要随机化的值掷骰子。

最佳答案

使用 np.random.choice 和要屏蔽的元素数量 -

import numpy as np

mask = example_array == 5
select_nums = np.r_[:5,6:10] # array from which elements are to be picked up
# we need to skip number 5, so we are using np.r_
# to concatenate range arrays
example_array[mask] = np.random.choice(select_nums, mask.sum())

关于python - 将掩码结果转换为不同的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53465682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com