title: Pandas: Select First 3 Rows With Distinct Values in Specific Column
body: <p>I'm working with a Pandas dataframe like this:</p>
  
  <pre><code>  col1 col2 id  name
  0   1   2   1   harry
  1   2   3   1   harry
  2   3   4   2   harry
  3   4   5   3   harry
  4   5   6   4   harry
  5   1   9   6   jane
  6   2   10  6   jane
  7   3   11  7   jane
  8   4   12  7   jane
  9   5   12  8   jane
  </code></pre>
  
  <p>I'd like to create a new dataframe where, for each <code>name</code>, I take the first 3 rows with unique <code>id</code> values.</p>
  
  <p>For instance, for <code>harry</code>, this would be rows 0, 2, and 3.  Row 1 is excluded since it has the same id as row 0.</p>
  
  <p>The correct output for my example dataframe is:</p>
  
  <pre><code>  col1 col2 id  name
  0   1   2   1   harry
  2   3   4   2   harry
  3   4   5   3   harry
  5   1   9   6   jane
  7   3   11  7   jane
  9   5   12  8   jane
  </code></pre>
  
  <p>Example dataframe is given by this code:</p>
  
  <pre><code>example = pd.DataFrame({"col1":[1,2,3,4,5, 1,2,3,4,5], "id":[1,1,2,3,4, 6, 6, 7, 7, 8],
                          "col2":[2,3,4,5,6, 9, 10, 11, 12, 12],
                          "name":["harry", "harry", "harry", "harry", "harry", "jane",
                                 "jane","jane","jane","jane",]})
  </code></pre>
  
  <p>This code works but is very ugly and not vectorized:</p>
  
  <pre><code>result_df = pd.DataFrame(columns=example.columns)
  names_to_ids = {}
  for i, row in example.iterrows():
      curr_name = row["name"]
      curr_id = row["id"]
      print curr_name, curr_id
      if curr_name not in names_to_ids:
          result_df = result_df.append(row)
          names_to_ids[curr_name] = [curr_id]
      elif len(names_to_ids[curr_name]) &lt; 3 and curr_id not in names_to_ids[curr_name]:
          result_df = result_df.append(row)
          names_to_ids[curr_name].append(curr_id)
  </code></pre>