Python - Sort descending dataframe with pandas

Learn, how can we sort by in the opposite fashion that is in the descending order? By Pranit Sharma Last updated : September 27, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Sorting refers to rearranging a series or a sequence in a particular fashion (ascending, descending, or in any specific pattern).

Sort descending dataframe with pandas

Sorting in pandas DataFrame is required for effective analysis of the data. We will use df.sort_values() method for this purpose, Pandas df.sort_values() method is used to sort a data frame in Ascending or Descending order. Since a data particular column cannot be selected, it is different than the sorted() Python function since it cannot sort

The syntax of df.sort_values() method is:

DataFrame.sort_values(
    by, 
    axis=0, 
    ascending=True, 
    inplace=False, 
    kind='quicksort', 
    na_position='last'
    )

The parameter(s) of df.sort_values() method are:

  • by: column or list of columns to sort DataFrame by.
  • axis: either 1 or 0, means row-wise or column-wise
  • ascending: if true, it will sort in ascending order or vice-versa.

Here, we will pass ascending = False as a parameter inside the "df.sort_values() method to sort in descending order.

Let us understand with the help of an example,

Python program to sort descending dataframe with pandas

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'A':[10,20,30,40,50],
    'B':[-32,58,-11,20,-9]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original DataFrame
print("Created DataFrame:\n",df,"\n")

# Sorting in descending order
result = df.sort_values(['B'], ascending=False)

# Display result
print("Result:\n",result)

Output

The output of the above program is:

Example: Sort descending dataframe with pandas

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.