2016-09-30 8 views
2

パンダのデータフレームを無作為にサンプリングしたい場合はpandas.DataFrame.sampleを使用できます。パンダのサンプリング

ランダムに80%の行をサンプリングするとします。選択されなかった行の20%を自動的に取得するにはどうすればよいですか?

+1

交換するかどうかをサンプリングしていますか? 置換なしでサンプリングする場合:一意のインデックスを持つ列をデータフレームに追加するだけです。次に、どのインデックス番号があなたの80%で選ばれたかを見て、残りの20%を得るためにそれを使用します。 – Lagerbaer

+0

また、データフレーム全体をシャッフル*する方法、つまりすべての行をランダム化してから、行80:20を分割する方法があります。 – Lagerbaer

+0

交換なし – wwl

答えて

3

Lagerbaerが説明しているように、一意のインデックスを持つ列をデータフレームに追加したり、データフレーム全体をランダムにシャッフルしたりすることができます。後者については、

df.reindex(np.random.permutation(df.index)) 

があります。 (npはnumpyを意味します)

2
>>> import pandas as pd, numpy as np 
>>> df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8,9,10], 'b': [11,12,13,14,15,16,17,18,19,20]}) 
>>> df 
    a b 
0 1 11 
1 2 12 
2 3 13 
3 4 14 
4 5 15 
5 6 16 
6 7 17 
7 8 18 
8 9 19 
9 10 20 

# randomly sample 5 rows 
>>> sample = df.sample(5) 
>>> sample 
    a b 
7 8 18 
2 3 13 
4 5 15 
0 1 11 
3 4 14 

# list comprehension to get indices not in sample's indices 
>>> idxs_not_in_sample = [idx for idx in df.index if idx not in sample.index] 
>>> idxs_not_in_sample 
[1, 5, 6, 8, 9] 

# locate the rows at the indices in the original dataframe that aren't in the sample 
>>> not_sample = df.loc[idxs_not_in_sample] 
>>> not_sample 
    a b 
1 2 12 
5 6 16 
6 7 17 
8 9 19 
9 10 20 
関連する問題