Amrith Krishna
Amrith Krishna

Reputation: 2853

Efficient numpy approach to iterate through elements of numpy arrays

With the following code snippet, I am trying to generate a vector where each element of it is drawn from a different normal distribution. The "mean" and "standard deviation" (arguments to random.normal) values for this is obtained from 2 numpy vectors, meanVect and varVect. Both the vectors have the same shape as that of vector to be generated.

I am using list comprehension to achieve the same, which I have used as a quicj and dirty fix to achieve my objective. Is there a numpy specific approach to achieve the same, which is more efficient than my current solution.

from numpy import random
meanVect = np.random.rand(1,100) # using random vectors for MWE
varVect = np.random.rand(1,100)  # Originally vectors from a different source is used
newVect = [random.normal(meanVect[i],varVect[i]) for i in range(len(meanVects[0])) ]

Upvotes: 0

Views: 45

Answers (1)

Daniel F
Daniel F

Reputation: 14399

Since np.random.normal takes array-like inputs for loc and scale, you can just do:

newVect = np.random.normal(meanVect, varVect)

As long as both input vectors have the same .shape, this should work.

Upvotes: 2

Related Questions