mercredi 4 mai 2022

Efficiently random set matrix elements in numpy

I have a boolean matrix in numpy with shape (m, n).

I initialize the matrix elements to be False.

I want to randomly set exactly x elements in each row (x < n) with the value True.

Now I go over the matrix with a loop, using np.random.choice with no replacement:

mat = np.full((M, N), fill_value=False)
for i in range(mat.shape[0]):
    mat[i, np.random.choice(mat.shape[1], x, replace=False)] = True

Is there a more efficient way to do this with numpy?




Aucun commentaire:

Enregistrer un commentaire