2016-12-15 2 views
1

「ラベル」列のクラス= 1の「のみ」から2行をサンプルしたいとします。あなたがいることがわかります私のコードでPythonの特定のクラスから行数をサンプリングするには?

1)私は、クラス= 1(4行)

2)からすべての行をサンプリングそれから私は、以前のデータフレーム

から2行をサンプリングしかし、私はこれを行うより良い方法がなければならないと確信しています。

# Creation of the dataframe 
df = pd.DataFrame(np.random.rand(12, 5)) 
label=np.array([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]) 
df['label'] = label 


# Sampling 
df1=df.loc[df['label'] == 1] #Extract ALL samples with class=1 
df2 = pd.concat(g.sample(2) for idx, g in df1.groupby('label')) #Extract 2 samples from df1 
df2 

enter image description here

enter image description here

答えて

3

私はこれを行うだけだろう:

df1.query('label == 1').sample(2) 

enter image description here

+1

注これはあなたがすでにやっていることと等価であること(サンセリフ無意味な 'groupby'操作)。あなたがすでに持っている解決策には何も問題はありません。 –

関連する問題