Pandas隨機采樣


實現對DataFrame對象隨機采樣

pandas是基於numpy建立起來的,所以numpy大部分函數可作用於DataFrame和Series數據結構。

numpy.random.permutation(n)函數可以產生0~n范圍內的n個隨機數,輸出形式為numpy數組。

In:

import numpy as np
sampler = np.random.permutation(10)
sampler

Out:

array([7, 6, 0, 8, 2, 5, 3, 1, 9, 4])

新建一個(10 * 5) DataFrame對象,然后隨機從中抽取5行

In:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(50).reshape(10,5))
df

Out:

In:

sample_df = np.random.permutation(len(df))
sample_df

Out:

array([9, 4, 6, 8, 3, 5, 0, 1, 7, 2])

使用Pandas的take函數作用於數組sample_df,結果是對df進行了隨機排序,選取5行

In:

df_new = df.take(sample_df[:5])
df_new

out:

結果是隨機選出來的(5*5)的新DataFrame對象

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM