Python Pandas - Sort DataFrame in ascending order according to the element frequency


To sort data in ascending or descending order, use sort_values() method. For ascending order, use the following is the sort_values() method −

ascending=True

Import the required library −

import pandas as pd

Create a DataFrame with 3 columns −

dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000],"Place": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh']
   }
)

To sort DataFrame in ascending order according to the element frequency, we need to count the occurrences. Therefore, count() is also used with sort_values() set for asscending order sort −

dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=True)

Example

Following is the code −

import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000],"Place": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh']
   }
)

print"DataFrame ...\n",dataFrame

# Sort DataFrame in ascending order according to the element frequency
dataFrame = dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=True)

print"\nSorting DataFrame in ascending order ...\n",dataFrame

Output

This will produce the following output −

DataFrame ...
        Car      Place   Reg_Price
0       BMW       Pune        7000
1     Lexus      Delhi        1500
2       BMW     Mumbai        5000
3   Mustang  Hyderabad        8000
4  Mercedes  Bangalore        9000
5     Lexus Chandigarh        2000

Sorting DataFrame in ascending order ...
        Car   Count
2  Mercedes       1
3   Mustang       1
0       BMW       2
1     Lexus       2

Updated on: 20-Sep-2021

639 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements