title: Sorting columns and selecting top n rows in each group pandas dataframe
body: <p>I have a dataframe like this: </p>
  
  <pre><code>mainid  pidx    pidy   score
    1      a        b      2
    1      a        c      5
    1      c        a      7
    1      c        b      2
    1      a        e      8
    2      x        y      1
    2      y        z      3
    2      z        y      5
    2      x        w      12
    2      x        v      1
    2      y        x      6   
  </code></pre>
  
  <p>I want to <code>groupby on column 'pidx'</code>  and then <code>sort score in descending order in each group</code> i.e for each pidx</p>
  
  <p>and then <code>select head(2)</code> i.e top 2 from each group.</p>
  
  <p>The result I am looking for is like this:</p>
  
  <pre><code>mainid   pidx    pidy    score
    1        a      e        8
    1        a      c        5
    1        c      a        7
    1        c      b        2
    2        x      w        12
    2        x      y        1
    2        y      x        6
    2        y      z        3
    2        z      y        5
  </code></pre>
  
  <p>What I tried was:</p>
  
  <pre><code>df.sort(['pidx','score'],ascending = False).groupby('pidx').head(2) 
  </code></pre>
  
  <p>and this seems to work, but I dont know if it's the right approach if working on a huge dataset. What other best method can I use to get such result? </p>