To sort data in ascending or descending order, use sort_values() method. For descending order, use the following in the sort_values() method −
ascending=False
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 descending order according to the element frequency, we need to count the occurrences. Therefore, count() is also used with sort_values() set for descending order sort −
dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False)
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 descending order according to the element frequency dataFrame = dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False) print"\nSorting DataFrame ...\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 ... Car Count 0 BMW 2 1 Lexus 2 2 Mercedes 1 3 Mustang 1