Python 将屏蔽结果转换为不同的随机数

Python 将屏蔽结果转换为不同的随机数,python,arrays,numpy,vectorization,mask,Python,Arrays,Numpy,Vectorization,Mask,我想做这样的事 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.

我想做这样的事

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]

这似乎是一件应该很容易做到的事情,但我不知道如何有效地做到这一点。为了提高速度,我想用面具。我目前正在使用的(而且速度非常慢!)方法是在数组上循环并掷骰子寻找任何需要随机化的值。

使用
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())

非常感谢你。这帮助我的游戏地图生成速度提高了182%!我投了更高的票,但我是新的,所以不幸的是它暂时被隐藏了。