pandas隨機排列與隨機抽樣

隨機排列

利用 numpy.random.permutation() 函數,能夠返回一個序列的隨機排列。將此隨機排列做爲 take() 函數的參數,經過應用 take() 函數就可實現按此隨機排列來調整 Series 對象或 DataFrame 對象各行的順序。
其示例代碼 example1.py 以下:dom

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)spa

函數中的參數說明以下:code

  • 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
相關文章
相關標籤/搜索