任意排列
运用 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