0

I have a numpy array,

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

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

Aim: Each value should have a probability of changing, p = 0.05, and the value it changes to is given by a sample from a normal distribution with mean = 1, st.dev = 0.2

So far, I have tried following This:

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

This does change values randomly with p = 0.05 ,but all values are the same, which is not ideal.

So, how does one go about making sure that each sampled value is independent(without using for loop)?

6
  • Just use np.random.seed(1), this will should be enough to get different values. Commented Aug 21, 2021 at 6:16
  • 2
    @Gray_Rhino That doesn't do anything to address his issue. Commented Aug 21, 2021 at 6:23
  • You have to use a for loop. The problem is you don't know how many numbers you'll need until the left side of the = is evaluated, and by then it's too late. Commented Aug 21, 2021 at 6:24
  • @Gray_Rhino, that would not work, I think the issue lies in the "rng.normal(loc=1,scale=0.2)". it gets a single output and sets it for all changing indices rather than sampling independently for every index Commented Aug 21, 2021 at 6:27
  • @TimRoberts for loop seems the only way then Commented Aug 21, 2021 at 6:28

1 Answer 1

0
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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.