Pandas sort dataframe by column with strings and integers
<p>I have a dataframe with a column containing both integers and strings:</p>

<pre><code>&gt;&gt;&gt; df = pd.DataFrame({'a':[2,'c',1,10], 'b':[5,4,0,6]})
&gt;&gt;&gt; df
    a  b
0   2  5
1   c  4
2   1  0
3  10  6
</code></pre>

<p>I want to sort the dataframe by column a, treating the strings and integers separately, with strings first:</p>

<pre><code>&gt;&gt;&gt; df
    a  b
1   c  4
2   1  0
0   2  5
3  10  6
</code></pre>

<p>...but Python doesn't allow comparing integers to strings.</p>

<pre><code>TypeError: unorderable types: int() &gt; str()
</code></pre>

<p>If I first convert all the integers to strings, I don't get what I want:</p>

<pre><code>&gt;&gt;&gt; df.a = df.a.astype(str)
&gt;&gt;&gt; df.sort(columns='a')
    a  b
0   1  0
3  10  6
2   2  5
1   c  4
</code></pre>

<p>Does anyone know of a one-line way to tell Pandas that I want it to sort strings first, then integers, without first breaking the dataframe into pieces?</p>

<p>One option would be to group the data frame by the data type of column <code>a</code> and then sort each group separately:</p>

<pre><code>df.groupby(df.a.apply(type) != str).apply(lambda g: g.sort('a')).reset_index(drop = True)
</code></pre>

<p><a href="https://i.stack.imgur.com/cwuCV.png" rel="nofollow"><img src="https://i.stack.imgur.com/cwuCV.png" alt="enter image description here"></a></p>

python sorting pandas