...

/

Performing Sorting

Performing Sorting

Learn how to sort data using Python.

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:

Press + to interact
main.py
employees.csv
import pandas as pd
employees_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 WEIGHT column using the sort_values() method. The sort_values() method takes a single parameter: the column name to sort by. In this case, ...