Sorting a Pandas Dataframe by a Specific Column
Consider the following dataframe, where the months are not in chronological order:
0 1 2<br>0 354.7 April 4.0<br>1 55.4 August 8.0<br>2 176.5 December 12.0<br>3 95.5 February 2.0<br>4 85.6 January 1.0<br>5 152 July 7.0<br>6 238.7 June 6.0<br>7 104.8 March 3.0<br>8 283.5 May 5.0<br>9 278.8 November 11.0<br>10 249.6 October 10.0<br>11 212.7 September 9.0<br>
To rectify this, a second column with the corresponding month numbers (1-12) is created. The objective is to sort the dataframe based on the calendar month order.
The solution lies in using the sort_values method:
<br>df.sort_values('2')<br>
This command sorts the dataframe ascendingly by the values in the '2' column:
</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> 0 1 2
4 85.6 January 1.0
3 95.5 February 2.0
7 104.8 March 3.0
0 354.7 April 4.0
8 283.5 May 5.0
6 238.7 June 6.0
5 152.0 July 7.0
1 55.4 August 8.0
11 212.7 September 9.0
10 249.6 October 10.0
9 278.8 November 11.0
2 176.5 December 12.0
To sort by multiple columns, provide a list of column labels in the order of sort priority as an argument to sort_values.
The above is the detailed content of How to Sort a Pandas DataFrame by a Specific Column?. For more information, please follow other related articles on the PHP Chinese website!