隨機排列
利用 numpy.random.permutation() 函式,可以回傳一個序列的隨機排列,將此隨機排列作為 take() 函式的引數,通過應用 take() 函式就可實作按此隨機排列來調整 Series 物件或 DataFrame 物件各行的順序,
其示例代碼 example1.py 如下:
import numpy as np import pandas as pd #創建DataFrame df = pd.DataFrame(np.arange(12).reshape(4,3)) print(df) 0 1 2 0 0 1 2 1 3 4 5 2 6 7 8 3 9 10 11 #創建隨機排列 order = np.random.permutation(4) #通過隨機排列調整DataFrame各行順序 newDf = df.take(order) print(newDf) 0 1 2 2 6 7 8 3 9 10 11 0 0 1 2 1 3 4 5
隨機抽樣
隨機抽樣是指隨機從資料中按照一定的行數或者比例抽取資料,隨機抽樣的函式如下:
numpy.random.randint(start,end,size)
函式中的引數說明如下:
- start:亂數的開始值;
- end:亂數的終止值;
- size:抽樣個數,
通過 numpy.random.randint() 函式產生隨機抽樣的資料,通過應用 take() 函式就可實作隨機抽取 Series 物件或 DataFrame 物件中的資料,其示例代碼 example2.py 如下
import numpy as np import pandas as pd #創建DataFrame df = pd.DataFrame(np.arange(12).reshape(4,3)) print(df) 0 1 2 0 0 1 2 1 3 4 5 2 6 7 8 3 9 10 11 #隨機抽樣 order = np.random.randint(0,len(df),size=3) #通過隨機抽樣抽取DataFrame中的行 newDf = df.take(order) print(newDf) 0 1 2 0 0 1 2 1 3 4 5 1 3 4 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/251399.html
標籤:Python
