title: How to sort pandas DataFrame with a key?
body: <p>I'm looking for a way to sort pandas DataFrame. <code>pd.DataFrame.sort_values</code> doesn't accept a key function. I can convert it to list and apply a key to <code>sorted</code> function, but that will be slow. The other way seems something related to categorical index. I don't have a fixed number of rows so I don't know if categorical index will be applicable.</p>
  <p>I have given an example case of what kind of data I want to sort:</p>
  <p><strong>Input DataFrame:</strong></p>
  <pre><code>     clouds  fluff
  0    {[}      1
  1    &gt;&gt;&gt;      2
  2     {1      3
  3    123      4
  4  AAsda      5
  5    aad      6
  </code></pre>
  <p><strong>Output DataFrame:</strong></p>
  <pre><code>     clouds  fluff
  0    &gt;&gt;&gt;      2
  1    {[}      1
  2     {1      3
  3    123      4
  4    aad      6
  5  AAsda      5
  </code></pre>
  <p><strong>The rule for sorting (priority):</strong></p>
  <blockquote>
  <ul>
  <li><p>First special characters (sort by ascii among themselves)</p>
  </li>
  <li><p>Next is by numbers</p>
  </li>
  <li><p>next is by lower case alphabets (lexicographical)</p>
  </li>
  <li><p>next is Capital case alphabets (lexicographical)</p>
  </li>
  </ul>
  </blockquote>
  <p><strong><em>In plain python I'd do it like</em></strong></p>
  <pre><code>from functools import cmp_to_key
  
  def ks(a, b):
      # &quot;Not exactly this but similar&quot;
      if a.isupper():
          return -1
      else:
          return 1
  </code></pre>
  <p><strong>Case</strong></p>
  <pre><code>sorted(['aa', 'AA', 'dd', 'DD'], key=cmp_to_key(ks))
  </code></pre>
  <p><strong>Answer:</strong></p>
  <pre><code>['DD', 'AA', 'aa', 'dd']
  </code></pre>
  <p>How would you do it with Pandas?</p>