Use sort_values() to reorder rows by column values. Apply sort_index() to rearrange rows by the DataFrame’s index. Combine both methods to explore your data from different angles.
Finding interesting bits of data in a DataFrame is often easier if you change the rows' order. You can sort the rows by passing a column name to .sort_values().
In cases where rows have the same value (this is common if you sort on a categorical variable), you may wish to break the ties by sorting on another column. You can sort on multiple columns in this way by passing a list of column names.
Sorting Rows by Column Values with sort_values()
You can change the rows' order by sorting them so that the most interesting data is at the top of the DataFrame.
Sort by a single column
For example, when we apply sort_values() on the weight_kg column of the dogs DataFrame, we get the lightest dog at the top, Stella the Chihuahua, and the heaviest dog at the bottom, Bernie the Saint Bernard.
name breed color height_cm weight_kg date_of_birth
5 Stella Chihuahua Tan 1822015-04-203 Cooper Schnauzer Gray 49172011-12-110 Bella Labrador Brown 56242013-07-011 Charlie Poodle Black 43242016-09-162 Lucy Chow Chow Brown 46242014-08-254 Max Labrador Black 59292017-01-206 Bernie St. Bernard White 77742018-02-27
name breed color height_cm weight_kg date_of_birth
6 Bernie St. Bernard White 77742018-02-274 Max Labrador Black 59292017-01-200 Bella Labrador Brown 56242013-07-011 Charlie Poodle Black 43242016-09-162 Lucy Chow Chow Brown 46242014-08-253 Cooper Schnauzer Gray 49172011-12-115 Stella Chihuahua Tan 1822015-04-20
We can sort by multiple variables by passing a list of column names to sort_values. Here, we sort first by weight, then by height. Now, Charlie, Lucy, and Bella are ordered from shortest to tallest, even though they all weigh the same.
name breed color height_cm weight_kg date_of_birth
5 Stella Chihuahua Tan 1822015-04-203 Cooper Schnauzer Gray 49172011-12-111 Charlie Poodle Black 43242016-09-162 Lucy Chow Chow Brown 46242014-08-250 Bella Labrador Brown 56242013-07-014 Max Labrador Black 59292017-01-206 Bernie St. Bernard White 77742018-02-27
To change the direction values are sorted in, pass a list to the ascending argument to specify which direction sorting should be done for each variable. Now, Charlie, Lucy, and Bella are ordered from tallest to shortest.
name breed color height_cm weight_kg date_of_birth
5 Stella Chihuahua Tan 1822015-04-203 Cooper Schnauzer Gray 49172011-12-110 Bella Labrador Brown 56242013-07-012 Lucy Chow Chow Brown 46242014-08-251 Charlie Poodle Black 43242016-09-164 Max Labrador Black 59292017-01-206 Bernie St. Bernard White 77742018-02-27
Sometimes you may want to reorder rows based on their row labels (i.e., the DataFrame’s index) rather than by specific columns. If that is the case, you can use the sort_index() method instead of sort_values(). Remember that, by default, sort_index() will sort your rows in ascending order by their index:
# Sort rows by their index (ascending)
dogs_sorted = dogs.sort_index()print(dogs_sorted)제공
If you need to sort the rows in descending order, just pass ascending=False:
# Sort rows by their index (descending)
dogs_sorted_desc = dogs.sort_index(ascending=False)print(dogs_sorted_desc)제공
Similarly, if you have a multi-level (hierarchical) index, sort_index() can also handle that by sorting multiple levels. You just pass a list to the level or ascending parameters (just like earlier we had to pass a list for sort_values()):
# Sort rows by multiple levels of a multi-level index
dogs_sorted_multi = dogs.sort_index(level=[0,1], ascending=[True,False])print(dogs_sorted_multi)제공
Pandas Sort Values Interactive Example
In the following example, you will sort homelessness by the number of homeless individuals, from smallest to largest, and save this as homelessness_ind. Finally, you will print the head of the sorted DataFrame.
# Sort homelessness by individuals
homelessness_ind = homelessness.sort_values("individuals")# Print the top few rowsprint(homelessness_ind.head())
When we run the above code, it produces the following result:
region state individuals family_members state_pop
50 Mountain Wyoming 434.0205.057760134 West North Central North Dakota 467.075.07580807 South Atlantic Delaware 708.0374.096547939 New England Rhode Island 747.0354.0105828745 New England Vermont 780.0511.0624358
We have learned in this article, among other things, when to use sort_index() vs. sort_values(): Use sort_values() when you want to reorder rows based on column values; use sort_index() when you want to reorder rows based on the row labels (the DataFrame’s index).
Explore data analysis with Python. Pandas DataFrames make manipulating your data easy, from selecting or replacing columns and indices to reshaping your data.
Learn the pandas reset_index() method to reset the index of a DataFrame. Explore the different options available with this method and how to reset the index for simple and multi-level DataFrame.
Learn how to rename columns in pandas with .rename(), df.columns, and .set_axis(), plus Python functions for snake_case and fixes for KeyError and ValueError.
Finding interesting bits of data in a DataFrame is often easier if you change the rows' order. You can sort the rows by passing a column name to
.sort_values().In cases where rows have the same value (this is common if you sort on a categorical variable), you may wish to break the ties by sorting on another column. You can sort on multiple columns in this way by passing a list of column names.
Sorting Rows by Column Values with sort_values()
You can change the rows' order by sorting them so that the most interesting data is at the top of the DataFrame.
Sort by a single column
For example, when we apply
sort_values()on theweight_kgcolumn of the dogs DataFrame, we get the lightest dog at the top, Stella the Chihuahua, and the heaviest dog at the bottom, Bernie the Saint Bernard.Setting the
ascendingargument to False will sort the data the other way round, from heaviest to lightest dog.Sort by multiple columns
We can sort by multiple variables by passing a list of column names to
sort_values. Here, we sort first by weight, then by height. Now, Charlie, Lucy, and Bella are ordered from shortest to tallest, even though they all weigh the same.To change the direction values are sorted in, pass a list to the ascending argument to specify which direction sorting should be done for each variable. Now, Charlie, Lucy, and Bella are ordered from tallest to shortest.
Sorting by the Row Index with sort_index()
Sometimes you may want to reorder rows based on their row labels (i.e., the DataFrame’s index) rather than by specific columns. If that is the case, you can use the
sort_index()method instead ofsort_values(). Remember that, by default,sort_index()will sort your rows in ascending order by their index:If you need to sort the rows in descending order, just pass
ascending=False:Similarly, if you have a multi-level (hierarchical) index,
sort_index()can also handle that by sorting multiple levels. You just pass a list to thelevelorascendingparameters (just like earlier we had to pass a list forsort_values()):Pandas Sort Values Interactive Example
In the following example, you will sort
homelessnessby the number of homeless individuals, from smallest to largest, and save this ashomelessness_ind. Finally, you will print the head of the sorted DataFrame.When we run the above code, it produces the following result:
Try it for yourself.
To learn more about sorting and subsetting the data, please see this video from our course Data Manipulation with pandas.
This content is taken from DataCamp’s Data Manipulation with pandas course by Maggie Matsui and Richie Cotton.
Further Learning
We have learned in this article, among other things, when to use
sort_index()vs.sort_values(): Usesort_values()when you want to reorder rows based on column values; usesort_index()when you want to reorder rows based on the row labels (the DataFrame’s index).We have many other useful pandas tutorials so you can keep learning, including The ultimate Guide to Pandas for Beginners, so you can keep practicing. We also have other specific how-to's for common issues, including How to Import CSV Data into Pandas and How to Join DataFrames in Pandas. Also, remember to take our Python Programming skill track to keep improving your skills.