python - 在python中如何以一定的概率随机替换数组的特定元素?

标签 python numpy

对于这样的数组:

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/

相关文章:

python - SQLite Python AND 语句不起作用

python - 如何导入具有复杂字段的csv

python - 2.5//2.0 在 Python 3.x 中返回 float 而不是 int 背后的基本原理是什么?

python列表+空numpy数组=空numpy数组?

python - 通过删除缺失元素来压缩 pandas 数据框

python - 使用多个分隔符/条件拆分列表的字符串元素。有什么好的Python库吗?

python - 在Python中使用ftplib将文件传输到FTP服务器时获取 "Connection refused"

python - 在 NumPy 1.14 中将结构化数组的切片转换为常规 NumPy 数组

python - 将 'while' 循环中的数据存储在数组中

numpy - 受约束的 np.polyfit