如何以给定概率并基于分布更改 numpy 数组中的值?

How to change values in a numpy array with a given probability and based on a distribution?

我有一个 numpy 数组,

a = np.zeros((5,2))

a = array([[0., 0.],
           [0., 0.],
           [0., 0.],
           [0., 0.],
           [0., 0.]])

目标:每个值都应该有一个变化的概率,p = 0.05,它变化到的值由均值 = 1 的正态分布样本给出, st.dev = 0.2

到目前为止,我尝试了以下 This:

a[np.random.rand(*a.shape) < 0.05] = rng.normal(loc=1,scale=0.2)

这确实会随着 p = 0.05 随机更改值,但所有值都相同,这并不理想。

那么,如何确保每个采样值都是独立的(不使用 for 循环)?

from scipy import stats

a = np.zeros((5,2))

a[:] = np.where(np.random.rand(*a.shape) < 0.05,
                stats.norm.rvs(loc=1,scale=0.2, size = a.shape),
                a)