简体   繁体   中英

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

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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM