Home >Backend Development >Python Tutorial >How Do I Perform Multi-Column Sorting in Pandas DataFrames?

How Do I Perform Multi-Column Sorting in Pandas DataFrames?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 13:31:12226browse

How Do I Perform Multi-Column Sorting in Pandas DataFrames?

Multi-Column Sorting in Pandas DataFrames

To sort a Pandas DataFrame by multiple columns, utilize the sort_values method, which has replaced sort as of version 0.20.0.

Syntax

df.sort_values(['column1', 'column2'], ascending=[True, False])

where:

  • ['column1', 'column2']: List of column names for sorting.
  • [True, False]: List of ascending flags (True for ascending, False for descending).

Example

Consider a DataFrame df with columns a, b, and c. To sort df by b in ascending order and c in descending order:

df.sort_values(['b', 'c'], ascending=[True, False])

This will arrange the rows in df such that values in column b are sorted in ascending order, and within each b group, values in column c are sorted in descending order.

In-Place Sorting

By default, sort_values does not modify the original DataFrame. To perform in-place sorting, add inplace=True to the method call:

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

This will modify df itself, replacing it with the sorted version.

The above is the detailed content of How Do I Perform Multi-Column Sorting in Pandas DataFrames?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn