Performing Sorting
Learn how to sort data using Python.
We'll cover the following...
We'll cover the following...
Sorting by one column
The sort_values() method lets us sort data in a DataFrame by one or more columns. For example, we can use this method to sort the following dataset by the WEIGHT column, as shown below:
C++
Files
import pandas as pdemployees_df = pd.read_csv('employees.csv')pd.set_option('display.max_columns', None)sorted_df = employees_df.sort_values("HEIGHT")print(sorted_df)
Let’s review the code line by line:
Lines 1–3: We import the pandas library, load the dataset, and display all the DataFrame columns.
Line 4: We then sort the DataFrame by the
WEIGHTcolumn using thesort_values()method. Thesort_values()method takes a single parameter: the column name to sort by. In this case, we sort the data in ascending order based on the values in theWEIGHTcolumn.Line 5: We print
sorted_dfto see the sorted records. ...