How to sort/ group a Pandas data frame by class label or any specific column
<pre><code>class col2 col3 col4 col5
1     4    5    5    5
4     4    4.5  5.5  6
1     3.5  5    6    4.5
3     3    4    4    4
2     3    3.5  3.8  6.1
</code></pre>

<p>I have used hypothetical data in the example. The shape of the real DataFrame is 6680x1900. I have clustered these data into <code>50</code> labeled classes (1 to 50). How can I sort this data in ascending order of <code>class</code> labels?</p>

<p>I have tried:</p>

<pre><code>df.groupby([column_name_lst])["class"]
</code></pre>

<p>But it fails with this error:</p>

<blockquote>
  <p>TypeError: You have to supply one of 'by' and 'level'</p>
</blockquote>

<p>How to solve this problem? Expected output is:</p>

<pre><code>class col2 col3 col4 col5
1     4    5    5    5
1     3.5  5    6    4.5
2     3    3.5  3.8  6.1
3     3    4    4    4
4     4    4.5  5.5  6
</code></pre>

<p>If you are starting with the data in your question:</p>

<blockquote>
<pre><code>class col2 col3 col4 col5
1     4    5    5    5
4     4    4.5  5.5  6
1     3.5  5    6    4.5
3     3    4    4     4
2     3   3.5   3.8   6.1
</code></pre>
</blockquote>

<p>And want to sort that, then it depends on whether <code>'class'</code> is an index or column. If index:</p>

<pre><code>df.sort_index()
</code></pre>

<p>should give you the answer. If column, follow <a href="http://stackoverflow.com/a/39653849/3765319">answer by @jezarael</a></p>

python sorting pandas dataframe group-by