santoku
santoku

Reputation: 3447

in python how to replace specific elements of array randomly with a certain probability?

For an array like this:

import numpy as np
x = np.random.randint(0, 2, (5,5))

How can I replace the ones with tens randomly with 0.3 probability? This is something I tried but I don't know if it is the best method

mask = np.random.rand(5, 5)<0.3
x[x==1 * mask] = 10

Upvotes: 1

Views: 336

Answers (1)

rrcal
rrcal

Reputation: 3752

You can get the places of matched value (x==1) and then replace using np.random.choice:

import numpy as np
np.random.seed(1) ## fixing seed for replicability
x = np.random.randint(0, 2, (5,5))

Out[1]:
array([[1, 1, 0, 0, 1],
       [1, 1, 1, 1, 0],
       [0, 1, 0, 1, 1],
       [0, 0, 1, 0, 0],
       [0, 1, 0, 0, 1]])


x1, y1 = np.where(x==1)
replace_v = np.random.choice([1.,10.],len(x1), p=[0.7,0.3])
x[x1,y1] = replace_v

Out[2]: 
array([[ 1,  1,  0,  0,  1],
       [10,  1,  1, 10,  0],
       [ 0, 10,  0, 10, 10],
       [ 0,  0,  1,  0,  0],
       [ 0,  1,  0,  0, 10]])

Upvotes: 2

Related Questions