Search⌘ K
AI Features

Sorting Columns and Indexes

Explore how to sort DataFrame rows by columns and indexes effectively in pandas. Understand using sort_values for multi-column sorting, applying custom key functions, and how sorting indexes enables slicing by name in your data analysis.

Sorting columns

The sort_values method allows us to sort the rows of a DataFrame by arbitrary columns. In this example, we sort our DataFrame by the political party in alphabetical order:

Python 3.8
print(pres.sort_values(by='Party'))

We can also sort by multiple columns, and we can specify whether each column should be sorted in ascending (the default) or descending order. Here we sort by the Party column in ascending alphabetic order and ...