Search⌘ K
AI Features

Performing Sorting

Explore how to perform data sorting in Python with pandas. Understand sorting by one or multiple columns, handle ties using secondary columns, and specify ascending or descending order. Gain practical skills to organize data efficiently for analysis.

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++
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 ...