To group columns in Pandas dataframe, use the groupby(). At first, let us create Pandas dataframe −
dataFrame = pd.DataFrame( { "Car": ["Audi", "Lexus", "Audi", "Mercedes", "Audi", "Lexus", "Mercedes", "Lexus", "Mercedes"], "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350] } )
Let us now group according to Car column −
res = dataFrame.groupby("Car")
After grouping, we will use functions to find the means Registration prices (Reg_Price) of grouped car names −
res.mean()
This calculates mean of the Registration price according to column Car.
Example
Following is the code −
import pandas as pd # dataframe with one of the columns as Reg_Price dataFrame = pd.DataFrame( { "Car": ["Audi", "Lexus", "Audi", "Mercedes", "Audi", "Lexus", "Mercedes", "Lexus", "Mercedes"], "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350] } ) print"DataFrame...\n",dataFrame # grouped according to Car res = dataFrame.groupby("Car") print"\nMean of Registration Price grouped according to Car names...\n",res.mean()
Output
This will produce the following output −
DataFrame... Car Reg_Price 0 Audi 1000 1 Lexus 1400 2 Audi 1100 3 Mercedes 900 4 Audi 1700 5 Lexus 1800 6 Mercedes 1300 7 Lexus 1150 8 Mercedes 1350 Mean of Registration Price grouped according to Car names... Reg_Price Car Audi 1266.666667 Lexus 1450.000000 Mercedes 1183.333333