对于这样的数组:
import numpy as np
x = np.random.randint(0, 2, (5,5))
如何以 0.3 的概率随机替换 10 位数?这是我尝试过的方法,但我不知道这是否是最好的方法
mask = np.random.rand(5, 5)<0.3
x[x==1 * mask] = 10
最佳答案
您可以获取匹配值(x==1
)的位置,然后使用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]])
关于python - 在python中如何以一定的概率随机替换数组的特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59806596/