Sampling from two Gaussian distributions with different probability in Python

Viewed 376

I am trying to generate 100 samples from 2 different Gaussian distributions, such that G1 occurs with probability 0.7 and G2 occurs with 0.3. I have the following code snippet:

from scipy.stats import norm
import numpy as np

x = [norm.rvs(0, 1, size=5), norm.rvs(10, 1, 5)]
draw = np.random.choice([0, 1], 100, p=[0.7, 0.3])
y = [x[i].rvs() for i in draw]
z = np.array(y)

When I compile this, I get the following error:

AttributeError: 'numpy.ndarray' object has no attribute 'rvs'

Is there something I am missing? Or, is there a fundamental flaw?

1 Answers

In this line

x = [norm.rvs(0, 1, size=5), norm.rvs(10, 1, 5)]

you are creating two arrays of random values. So in this line

[x[i].rvs() for i in draw]

you can't use those to create more random values (.rvs), since you have numpy arrays:

norm.rvs(0, 1, size=5)

# Out: array([-1.61758314,  1.19288111, -0.55599284, -0.17926848, -0.78759   ])

You want to create a list of normal distribution objects, which you then use to draw random values from:

x = [norm(0, 1), norm(10, 1)]
draw = np.random.choice([0, 1], 100, p=[0.7, 0.3])
y = [x[i].rvs() for i in draw]
Related