title: Python Pandas Choosing Random Sample of Groups from Groupby
body: <p>What is the best way to get a random sample of the elements of a <code>groupby</code>? As I understand it, a <code>groupby</code> is just an iterable over groups. </p>
  
  <p>The standard way I would do this for an iterable, if I wanted to select <code>N = 200</code> elements is:</p>
  
  <pre><code>rand = random.sample(data, N)  
  </code></pre>
  
  <p>If you attempt the above where data is a 'grouped' the elements of the resultant list are tuples for some reason.</p>
  
  <p>I found the below example for randomly selecting the elements of a single key <code>groupby</code>, however this does not work with a multi-key <code>groupby</code>. From, <a href="https://stackoverflow.com/questions/14734533/how-to-access-pandas-groupby-dataframe-by-key">How to access pandas groupby dataframe by key</a></p>
  
  <blockquote>
    <p>create groupby object</p>
  
  <pre><code>grouped = df.groupby('some_key')
  </code></pre>
    
    <p>pick N dataframes and grab their indices</p>
  
  <pre><code>sampled_df_i = random.sample(grouped.indices, N)
  </code></pre>
    
    <p>grab the groups using the groupby object 'get_group' method</p>
  
  <pre><code>df_list = map(lambda df_i: grouped.get_group(df_i),sampled_df_i)
  </code></pre>
    
    <p>optionally - turn it all back into a single dataframe object</p>
  
  <pre><code>sampled_df = pd.concat(df_list, axis=0, join='outer')
  </code></pre>
  </blockquote>