pandas: sort alphabetically if rows have same rank
<p>Say I have a dataframe with two rows that have the same value:</p>

<pre><code>testdf = pd.DataFrame({'a': ['alpha','beta','theta','delta','epsilon'],'b':[1,2,3,3,4]})

         a  b
0    alpha  1
1     beta  2
2    theta  3
3    delta  3
4  epsilon  4
</code></pre>

<p>Now I want to sort them based on column B:</p>

<pre><code>testdf['rank'] = testdf['b'].rank(ascending=False)

         a  b  rank
0    alpha  1   5.0
1     beta  2   4.0
2    theta  3   2.5
3    delta  3   2.5
4  epsilon  4   1.0
</code></pre>

<p>Since rows 2 and 3 have the same rank, I'd like to arrange them in alphabetical order for the viewer:</p>

<pre><code>         a  b  rank
0    alpha  1   5.0
1     beta  2   4.0
3    delta  3   2.5
2    theta  3   2.5
4  epsilon  4   1.0
</code></pre>

<p>But I'm not sure how to do this. Maybe I could group them by rank and order them...? I'm not sure how to do that in-place, though.</p>

<p>It's possible to sort by more than one column using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a>, what you want is to sort by <code>rank</code> first, then by the <code>a</code> column, and if you want it to happen inplace, we use <code>inplace=True</code> like below:</p>

<pre><code>In [14]: testdf.sort_values(['rank', 'a'], ascending=[False, True], inplace=True)

In [15]: testdf
Out[15]: 
         a  b  rank
0    alpha  1   5.0
1     beta  2   4.0
3    delta  3   2.5
2    theta  3   2.5
4  epsilon  4   1.0
</code></pre>

<p>Which is the result you want and inplace, if you don't use <code>inplace=True</code> the resulting dataframe will be returned from the operation.</p>

python pandas