Generate values in R and Python


I am trying to generate dummy data with some probability. Let say I want to have dummy data about people by gender. I already prepare this in R and you can see my code line below.

gender = sample(x=c("M","F"), prob = c(.6, .4),size=100,replace=TRUE)

Now I want to prepare the same thing but now in Python in Pandas Data Frame. Can anybody help me how to solve this problem?

Asked By: silent_hunter



You can use numpy.random.choice , replace is True by default.

>>> np.random.choice(a=["M", "F"], size=100, p=[0.6, 0.4])

array(['F', 'M', 'F', 'M', 'M', 'M', 'M', 'M', 'M', 'F', 'M', 'F', 'M',
       'M', 'F', 'M', 'M', 'M', 'F', 'F', 'M', 'M', 'F', 'F', 'M', 'F',
       'F', 'M', 'M', 'F', 'F', 'M', 'F', 'F', 'M', 'F', 'M', 'M', 'F',
       'M', 'M', 'F', 'F', 'M', 'M', 'F', 'M', 'M', 'F', 'M', 'M', 'M',
       'F', 'F', 'M', 'F', 'M', 'M', 'M', 'M', 'M', 'M', 'F', 'F', 'M',
       'M', 'F', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'F', 'M', 'F', 'F',
       'M', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'F', 'M', 'M', 'M', 'F',
       'F', 'F', 'F', 'F', 'M', 'M', 'F', 'F', 'F'], dtype='<U1')
Answered By: ThePyGuy

Try this. random.choices gets k choices from the iterable provided:

import random
print(random.choices("MF", weights=[.6,.4], k=100))


>>> l = random.choices("MF", weights=[.6,.4], k=100)
>>> l
['M', 'F', 'F', 'M', 'M', 'M', 'M', 'M', 'F', 'M', 'M', 'F', 'M', 'M', 'M', 'F', 'M', 'M', 'M', 'M', 'F', 'M', 'M', 'M', 'F', 'F', 'M', 'F', 'F', 'M', 'M', 'F', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'F', 'M', 'M', 'F', 'M', 'F', 'M', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'M', 'F', 'F', 'M', 'M', 'M', 'F', 'F', 'M', 'M', 'M', 'F', 'F', 'F', 'M', 'F', 'F', 'M', 'M', 'F', 'F', 'M', 'M', 'M', 'F', 'M', 'M', 'F', 'M', 'M', 'M', 'M', 'M', 'F', 'M', 'M', 'M', 'F', 'F', 'F', 'M', 'F', 'F', 'M']
>>> l.count("M")
>>> l.count("F")
Answered By: The Thonnu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.