Python学习笔记:利用sample函数实现随机抽样

一、random模块中的sample函数

  • 定义和用法

sample(L, n) 从序列L中随机抽取n个元素,并将n个元素以list形式返回。

此方法不会更改原始顺序。

  • 实例
import random
mylist = ['apple', 'banana', 'cherry']
print(random.sample(mylist, k=2))
# ['cherry', 'apple']
from random import randint, sample
data = [randint(10, 20) for _ in range(10)] # 列表推导式
result = sample(data, 5)
print(result)
# [13, 19, 15, 10, 15]
  • 补充

randint(a,b) 随机生成整数:[a-b]区间的整数,包含两端。

from random import randint
print("随机生成10个随机整数!")
i = 0
while True:
    i += 1
    print(randint(0, 10))
    if i == 10:
        break

for i in range(10):
    print(randint(0, 10))

二、numpy模块中的np.sample函数

  • 定义和用法

np.ramdom.sample(n) 返回半开区间 [0.0, 1.0) 之间随机的浮点数。

np.ramdom.random_sample(n) 同sample函数。

np.random.randint(low, high, size) 产生离散均匀分布的整数 [low, high) 半开半闭区间

np.random.choice(data, size, replace=False, p) 随机抽取 以p为概率在data中取size个值

  • 实例
import numpy as np
np.random.sample(10)
# array([0.45275115, 0.33643046, 0.55830306, 0.99455283, 0.40005534,
#       0.90456168, 0.82675439, 0.03287044, 0.10389054, 0.22584407])
np.random.random_sample() # 0.5290779045774395
np.random.random_sample(5)
# array([0.07298313, 0.16741836, 0.62372681, 0.19416871, 0.55995707])
# 返回0-5之间的二维数组
5 * np.random.random_sample((3, 2))
'''
array([[0.14137681, 3.92186577],
       [4.95626307, 3.06821623],
       [0.90562847, 4.23790207]])
'''

三、pandas模块中的pd.sample函数

实现对数据集的随机抽样,功能类似于 numpy.random.choice ,返回选择的n行数据的 DataFrame 对象。

  • 定义和用法
DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)
  • 参数说明
n -- 要抽取的行数 df.sample(n=3, random_state=1)
frac -- 抽取行的比例 frac=0.8 抽取其中80%
replace -- 是否为有放回抽样 True为有放回 False为未放回抽样
   注意:当n大于总数据量时,replace设置才生效
weights -- 字符索引或概率数组 代表样本权重
random_state -- int 随机数发生器种子 random_state=1 可重现过程
axis -- 选择抽取数据的行还是列 axis=0抽取行 axis=1抽取列
  • 实例
# 取样 sample
import pandas as pd
df.sample(n=108952*4, frac=None, replace=False, weights=None,
          random_state=1, axis=0)

四、对比

random.sample()np.random.choice() 两个函数都实现了从指定列表中提取N个不同的元素。区别之处在于:

  • 从对象类型看:random.sample 方法比 np.random.choice 方法适用范围广;

  • 从运行速度看:np.random.choice 用时基本不随数据量变化,而 random.sample 用时会随着抽样比例的增加而线性增长;

因此,当N值较大时,可以用 np.random.choice() 方法来提升随机提取的效率。

参考链接1:pandas.DataFrame.sample 随机选取若干行

参考链接2:pandas 随机抽取 DataFrame.sample()

原文地址:https://www.cnblogs.com/hider/p/14730750.html