简体   繁体   English

在 R 和 Python 中生成值

[英]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.我已经在 R 中准备了这个,你可以在下面看到我的代码行。

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.现在我想准备同样的东西,但现在在 Pandas 数据帧中的 Python 中。 Can anybody help me how to solve this problem?谁能帮我解决这个问题?

You can use numpy.random.choice , replace is True by default.您可以使用numpy.random.choice ,默认replaceTrue

>>> 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')

Try this.尝试这个。 random.choices gets k choices from the iterable provided: random.choices从提供的可迭代项中获取k个选项:

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

Testing:测试:

>>> 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")
60
>>> l.count("F")
40

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM