溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用pandas怎么實(shí)現(xiàn)一個隨機(jī)排列與隨機(jī)抽樣功能

發(fā)布時間:2021-01-25 16:25:29 來源:億速云 閱讀:236 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)使用pandas怎么實(shí)現(xiàn)一個隨機(jī)排列與隨機(jī)抽樣功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

隨機(jī)排列

利用 numpy.random.permutation() 函數(shù),可以返回一個序列的隨機(jī)排列。將此隨機(jī)排列作為 take() 函數(shù)的參數(shù),通過應(yīng)用 take() 函數(shù)就可實(shí)現(xiàn)按此隨機(jī)排列來調(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)建隨機(jī)排列
order = np.random.permutation(4)
#通過隨機(jī)排列調(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

隨機(jī)抽樣

隨機(jī)抽樣是指隨機(jī)從數(shù)據(jù)中按照一定的行數(shù)或者比例抽取數(shù)據(jù)。隨機(jī)抽樣的函數(shù)如下:

numpy.random.randint(start,end,size)

函數(shù)中的參數(shù)說明如下:

  • start:隨機(jī)數(shù)的開始值;

  • end:隨機(jī)數(shù)的終止值;

  • size:抽樣個數(shù)。

通過 numpy.random.randint() 函數(shù)產(chǎn)生隨機(jī)抽樣的數(shù)據(jù),通過應(yīng)用 take() 函數(shù)就可實(shí)現(xiàn)隨機(jī)抽取 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

#隨機(jī)抽樣
order = np.random.randint(0,len(df),size=3)
#通過隨機(jī)抽樣抽取DataFrame中的行
newDf = df.take(order)
print(newDf)
0 1 2
0 0 1 2
1 3 4 5
1 3 4 5

關(guān)于使用pandas怎么實(shí)現(xiàn)一個隨機(jī)排列與隨機(jī)抽樣功能就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI