Sort index alphabetically on first, second, third characters
<p>I have a df which looks like this:</p>

<pre><code>df = pd.DataFrame({'val': [0, 0, 0, 1, 0, 0, 0]}, 
                  index=['13th str', '3SAT', 'ARD', 
                         'ARD Dritte', 'AXNAction', 'Animal', 'bb'])
            val
13th str      0
3SAT          0
ARD           0
ARD Dritte    1
AXNAction     0
Animal        0
bb            0
</code></pre>

<p>I would like to sort it to look like this, </p>

<pre><code>            val
13th str      0
3SAT          0
Animal        0
ARD           0
ARD Dritte    1
AXNAction     0
bb            0
</code></pre>

<p>note - 'Animal' has shifted places.</p>

<p>If all the first letters are the same then look at the next character and so on. </p>

<p>Here is what I have tried which has not worked:</p>

<pre><code>df.sort()
df = df.sort_index()
df = df.index.sort_values() #gives an 'Index' object has no attribute 'sort_values' error
</code></pre>

<p>You can sort the index <a href="https://wiki.python.org/moin/HowTo/Sorting" rel="nofollow">using a custom <code>key</code> function</a>:</p>

<pre><code>In [22]: df = pd.DataFrame({'val': [0, 0, 0, 1, 0, 0, 0]}, 
              index=['13th str', '3SAT', 'ARD', 
                     'ARD Dritte', 'AXNAction', 'Animal', 'bb'])


In [23]: df

Out[23]: 

        val

13th str      0
3SAT          0
ARD           0
ARD Dritte    1
AXNAction     0
Animal        0
bb            0


In [24]: df.index = sorted(df.index.values, key=lambda s: s.lower())


In [25]: df

Out[25]: 
        val
13th str      0
3SAT          0
Animal        0
ARD           1
ARD Dritte    0
AXNAction     0
bb            0
</code></pre>

python sorting pandas dataframe