这仅仅是一个小笔记,之前没有用random
模块实现过这两个功能,这次主要是想实现一个无放回的抽样。搜狗一搜发现很多用循环语句写的解法(也不是不可以),但是也没必要重复造轮子啊。
首先导入random
模块并创建我们希望进行抽样的列表。
In [1]: import random
In [2]: l = list(range(20))
In [3]: l
Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
有放回抽样
有放回抽样主要使用random.choices()
方法,注意这个choice后面有s。
查看一下这个方法的帮助文档:
In [4]: help(random.choices)
Help on method choices in module random:
choices(population, weights=None, *, cum_weights=None, k=1) method of random.Random instance
Return a k sized list of population elements chosen with replacement.
If the relative weights or cumulative weights are not specified,
the selections are made with equal probability.
就是专门用于有放回抽样的一个方法,设定待抽样列表population
和希望抽样的长度k
即可。下面是抽样两次的结果。
In [5]: random.choices(l, k = 10)
Out[5]: [4, 3, 5, 3, 5, 2, 10, 6, 9, 5]
In [6]: random.choices(l, k = 10)
Out[6]: [17, 19, 13, 1, 15, 15, 19, 8, 0, 0]
无放回抽样
无放回抽样使用random.sample(population, k)方法。下面是抽样两次的结果。
In [8]: l
Out[8]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
In [9]: random.sample(l, 10)
Out[9]: [6, 14, 15, 8, 9, 5, 12, 3, 4, 7]
In [10]: random.sample(l, 10)
Out[10]: [19, 8, 13, 17, 9, 14, 15, 5, 18, 0]

Python实现有放回抽样和无放回抽样 由 赵匡是 采用 知识共享 署名 4.0 国际 许可协议进行许可。
本许可协议授权之外的使用权限可以从 关于知识产权 处获得。
沙发~~支持一下!