Python random sampling in multiple indices
<p>I have a data frame according to below:</p>

<pre>
id_1  id_2  value
1     0     1
1     1     2
1     2     3
2     0     4
2     1     1
3     0     5
3     1     1
4     0     5
4     1     1
4     2     6
4     3     7  
11    0     8
11    1     14
13    0     10
13    1     9 
</pre>

<p>I would like to take out a random sample of size n, without replacement, from this table based on <em>id_1</em>. This row needs to be unique with respect to the <em>id_1</em> column and can only occur once. </p>

<p>End result something like:</p>

<pre>
id_1  id_2  value
1     1     2
2     0     4
4     3     7
13    0     10

</pre>

<p>I have tried to do a group by and use the indices to take out a row through <em>random.sample</em> but it dosent go all the way. </p>

<p>Can someone give me a pointer on how to make this work? Code for DF below!</p>

<p>As always, thanks for time and input!</p>

<p>/swepab</p>

<pre><code>df = pd.DataFrame({'id_1' : [1,1,1,2,2,3,3,4,4,4,4,11,11,13,13],
               'id_2' : [0,1,2,0,1,0,1,0,1,2,3,0,1,0,1],
               'value_col' : [1,2,3,4,1,5,1,5,1,6,7,8,14,10,9]})
</code></pre>

<p>You can do this using vectorized functions (not loops) using </p>

<pre><code>import numpy as np

uniqued = df.id_1.reindex(np.random.permutation(df.index)).drop_duplicates()

df.ix[np.random.choice(uniqued.index, 1, replace=False)]
</code></pre>

<p><code>uniqued</code> is created by a random shuffle + choice of a unique element by <code>id_1</code>. Then, a random sample (without replacement) is generated on it.</p>

python sampling