一、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()
方法來提升隨機提取的效率。