title: Groupwise sorting in pandas
body: <p>I want to sort an array within the group boundaries defined in another array. The groups are not presorted in any way and need to remain unchanged after the sorting. In <code>numpy</code> terms it would look like this:</p>
  
  <pre><code>import numpy as np
  
  def groupwise_sort(group_idx, a, reverse=False):
      sortidx = np.lexsort((-a if reverse else a, group_idx))
      # Reverse sorting back to into grouped order, but preserving groupwise sorting
      revidx = np.argsort(np.argsort(group_idx, kind='mergesort'), kind='mergesort')
      return a[sortidx][revidx]
  
  group_idx =   np.array([3, 2, 3, 2, 2, 1, 2, 1, 1])
  a =           np.array([3, 2, 1, 7, 4, 5, 5, 9, 1])
  groupwise_sort(group_idx, a)
  # &gt;&gt;&gt;            array([1, 2, 3, 4, 5, 1, 7, 5, 9])
  groupwise_sort(group_idx, a, reverse=True)
  # &gt;&gt;&gt;            array([3, 7, 1, 5, 4, 9, 2, 5, 1])
  </code></pre>
  
  <p>How can I do the same with <code>pandas</code>? I saw <code>df.groupby()</code> and <code>df.sort_values()</code>, though I couldn't find a straight forward way to achieve the same sorting. And a fast one, if possible.</p>