Home >Backend Development >Python Tutorial >How to Sort a Pandas DataFrame by a Specific Column?

How to Sort a Pandas DataFrame by a Specific Column?

Linda Hamilton
Linda HamiltonOriginal
2024-12-16 08:07:14631browse

How to Sort a Pandas DataFrame by a Specific Column?

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>
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn