隨機排列
利用 numpy.random.permutation() 函數(shù),可以返回一個序列的隨機排列。將此隨機排列作為 take() 函數(shù)的參數(shù),通過應用 take() 函數(shù)就可實現(xiàn)按此隨機排列來調(diào)整 Series 對象或 DataFrame 對象各行的順序。
其示例代碼 example1.py 如下:
import numpy as np
import pandas as pd
#創(chuàng)建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
#創(chuàng)建隨機排列
order = np.random.permutation(4)
#通過隨機排列調(diào)整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
隨機抽樣
隨機抽樣是指隨機從數(shù)據(jù)中按照一定的行數(shù)或者比例抽取數(shù)據(jù)。隨機抽樣的函數(shù)如下:
numpy.random.randint(start,end,size)
函數(shù)中的參數(shù)說明如下:
- start:隨機數(shù)的開始值;
- end:隨機數(shù)的終止值;
- size:抽樣個數(shù)。
通過 numpy.random.randint() 函數(shù)產(chǎn)生隨機抽樣的數(shù)據(jù),通過應用 take() 函數(shù)就可實現(xiàn)隨機抽取 Series 對象或 DataFrame 對象中的數(shù)據(jù)。其示例代碼 example2.py 如下
import numpy as np
import pandas as pd
#創(chuàng)建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
以上就是詳解pandas隨機排列與隨機抽樣的詳細內(nèi)容,更多關(guān)于pandas隨機排列與隨機抽樣的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:- python使用pandas抽樣訓練數(shù)據(jù)中某個類別實例
- python Pandas如何對數(shù)據(jù)集隨機抽樣
- Pandas 數(shù)據(jù)框增、刪、改、查、去重、抽樣基本操作方法
- Pandas直接讀取sql腳本的方法
- python讀寫數(shù)據(jù)讀寫csv文件(pandas用法)
- pandas按照列的值排序(某一列或者多列)
- pandas抽取行列數(shù)據(jù)的幾種方法
- 使用pandas實現(xiàn)篩選出指定列值所對應的行