当条件为True
时,我试图得到一系列随机选择的数字。
我有一个充满布尔数的NumPy数组:
In [1]: multiples
Out[1]: array([False, False, False, True, True, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, True, True, True, True, False, False, False,
False, False, False, True, True, False, True, True, False,
False, False, False, True, True, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, True, True, False,
False, False, False, False, True, True, True, False, True,
True, False, False, False, True, True, False], dtype=bool)
我想根据条件将其转换为值数组:
如果值为
True
,则返回[-1, 0, 1]
中随机选择的数字,或返回0
。
所以在上面的例子中,我想输出看起来像:
Out[2]: array([ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, 0, 0, -1, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0,
1, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0])
numpy.where()
几乎给了我想要的东西:
In [3]: numpy.where(multiples, numpy.random.choice([-1, 0, 1], 1), 0)
Out[3]: array([ 0, 0, 0, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, 0,
0, 0, 0, 0, 0, -1, -1, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, 0,
-1, -1, -1, 0, -1, -1, 0, 0, 0, -1, -1, 0])
但问题是它只执行numpy.random.choice([-1, 0, 1], 1)
一次,并保留该结果并在任何地方使用它。我希望每次multiples
中的值为True
时都会运行它。
答案 0 :(得分:3)
out = np.random.randint(-1, 2, multiples.shape)
out[~multiples] = 0
答案 1 :(得分:2)
您可以使用np.random.choice
在列表[-1,0,1]
中生成随机数,并将它们放在输入数组中与True
位置对应的输出数组中,如下所示 -
newvals = [-1,0,1] # Values to be put at places of True in input array
out = np.zeros(multiples.size,dtype=int) # Setup output array
# Finally use np.random.choice to get random numbers from newvals as many
# as there are True elements in input array and put into the output array
# indexed by the corresponding True places in the input array
out[multiples] = np.random.choice(newvals, multiples.sum(), replace=True)
示例运行 -
In [44]: multiples
Out[44]:
array([ True, True, False, True, True, False, True, True, False,
True, False, True, False, True, True, True, True, False,
True, True], dtype=bool)
In [45]: newvals
Out[45]: [9, 10, 11]
In [46]: out
Out[46]:
array([11, 10, 0, 9, 9, 0, 10, 11, 0, 10, 0, 11, 0, 9, 10, 11, 9,
0, 10, 10])
答案 2 :(得分:0)
您是否尝试进行for循环?
for k in range(0,your x size):
for j in range(0, your y size):
if array[k][j] == True:
array[k][j] = (which value you want)
else:
array[k][j] = (which value you want)
如果您想录制,请将新的matris定义为A=np.zeros((xsize,ysize), 'uint8')
然后在第二个循环中添加A[k][j] = array[k][j]
。
显示它print (A)
会帮助你..