To sort a Pandas DataFrame by multiple columns, utilize the sort_values method, which has replaced sort as of version 0.20.0.
df.sort_values(['column1', 'column2'], ascending=[True, False])
where:
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.
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!