title: pandas - sort columns and group by a particular field
body: <p>I have a list of objects</p>
  <pre><code>[
     {
         &quot;companyid&quot;: long,
         &quot;parentid&quot;: long
         &quot;score&quot;: long,
         ...
     }
  ]
  </code></pre>
  <p>The parentid is nothing but the cid of the parent company<br />
  Sample data will look something like this</p>
  <pre><code>cid    parentid score
  1      10       1000  
  2      10       100
  3      10       1001  
  10     10       20  
  11     100      1000  
  12     100      100  
  100    100      200  
  111    1000     10  
  112    1000     100  
  1000   100      2000  
  </code></pre>
  <p>I need to sort the values based on the score, but i want to group the values by parentid<br />
  I tried this which didn't really fit my requirements, since it groups then sorts</p>
  <pre><code>df.groupby('headcompanyid').apply(lambda x: x.sort_values('score'))
  </code></pre>
  <p>Sorting by score will give this result:</p>
  <pre><code>cid    parentid score
  1000   100      2000 
  3      10       1001  
  1      10       1000  
  11     100      1000  
  100    100      200  
  2      10       100
  112    1000     100  
  12     100      100  
  10     10       20  
  111    1000     10  
  </code></pre>
  <p>Grouping by parentid on the sorted data (which is my end goal), should give this result</p>
  <pre><code>cid    parentid score
  1000   100      2000 
  11     100      1000    // since 100 is the parentid, it needs to be pushed up the in the result set
  100    100      200     // if multiple records are pushed up, then sorting should be based on score
  12     100      100  
  
  3      10       1001     // 2nd group by is based on 10, since 1001 is the next highest score which  
  1      10       1000     // doesn't belong to the 100 parentid group
  2      10       100 
  10     10       20 
  
  112    1000     100  
  111    1000     10 
  </code></pre>
  <p>i am using pandas v0.24.2 and python 3.7 if it matters</p>