Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Write a Python program to sort a given DataFrame by name column in descending order
Input −
Assume, sample DataFrame is,
Id Name 0 1 Adam 1 2 Michael 2 3 David 3 4 Jack 4 5 Peter
Output −
After, sorting the elements in descending order as,
Id Name 4 5 Peter 1 2 Michael 3 4 Jack 2 3 David 0 1 Adam
Solution
To solve this, we will follow the below approaches.
Define a DataFrame
Apply DataFrame sort_values method based on Name column and add argument ascending=False to show the data in descending order. It is defined below,
df.sort_values(by='Name',ascending=False)
Example
Let us see the following implementation to get a better understanding.
import pandas as pd
data = {'Id': [1,2,3,4,5],'Name': ['Adam','Michael','David','Jack','Peter']}
df = pd.DataFrame(data)
print("Before sorting:\n", df)
print("After sorting:\n", df.sort_values(by='Name',ascending=False))
Output
Before sorting: Id Name 0 1 Adam 1 2 Michael 2 3 David 3 4 Jack 4 5 Peter After sorting: Id Name 4 5 Peter 1 2 Michael 3 4 Jack 2 3 David 0 1 Adam
Advertisements
