从2d数组中选择随机索引



我想生成一个2d随机数组,并选择一些(m)随机索引,通过预定义值(m)来改变它们的值。

以这里为例,我想生成4 by 4矩阵。然后选择4随机索引,用[105,110,115,120]这个值修改它们的值。

random_matrix = np.random.randint(0,100,(4,4))
# array([[27, 20,  2,  8],
#        [43, 88, 14, 63],
#        [ 5, 55,  4, 72],
#        [59, 49, 84, 96]])

现在,我想随机选择4索引并从预定义的p_array = [105,110,115,120]

更改它们的值我尝试像这样生成所有的索引:

[
(i,j)
for i in range(len(random_matrix)) 
for j in range(len(random_matrix[i])) 
]

但是如何从中选择4随机索引并从预定义的p_matrix更改其值?我想不出任何解决方案,因为我必须确保4唯一的随机索引,我卡住了,因为随机性没有保证。

我们可以在一次拍摄中生成随机矩阵并选择指标吗?我需要这个,因为如果m的大小变得越来越大,它会变得越来越慢(目前的实现)。我还必须确保性能。

执行以下操作:

import numpy as np
# for reproducibility
np.random.seed(42)
rows, cols = 4, 4
p_array = np.array([105, 110, 115, 120])
# generate random matrix that will always include all the values from p_array
k = rows * cols - len(p_array)
random_matrix = np.concatenate((p_array, np.random.randint(0, 100, k)))
np.random.shuffle(random_matrix)
random_matrix = random_matrix.reshape((rows, cols))
print(random_matrix)

[[115  33  54  27]
[  3  27  16  69]
[ 33  24  81 105]
[ 62 110  94 120]]

假设与之前相同的设置,您可以执行以下操作来生成一个知道p_array值索引的随机矩阵:

positions = np.random.permutation(np.arange(rows * cols))
random_matrix = random_matrix[positions].reshape((rows, cols))
print("random-matrix")
print("-------------")
print(random_matrix)
print("-------------")
# get indices in flat array
flat_indices = np.argwhere(np.isin(positions, np.arange(4))).flatten()
# get indices in matrix
matrix_indices = np.unravel_index(flat_indices, (rows, cols))
print("p_array-indices")
print("-------------")
print(matrix_indices)
# verify that indeed those are the values
print(random_matrix[matrix_indices])

random-matrix
-------------
[[ 60  74  20  14]
[105  86 120  82]
[ 74  87 110  51]
[ 92 115  99  71]]
-------------
p_array-indices
-------------
(array([1, 1, 2, 3]), array([0, 2, 2, 1]))
[105 120 110 115]

您可以使用您建议的交叉产品和random.sample执行以下操作:

import random
from itertools import product
pool = [*product(range(len(random_matrix)), range(len(random_matrix[0])))]
random_indices = random.sample(pool, 4)
# [(3, 1), (1, 2), (2, 0), (2, 3)]

最新更新