
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Python - Grouping columns in Pandas Dataframe
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
- Related Articles
- Python - Name columns explicitly in a Pandas DataFrame
- Python - Renaming the columns of Pandas DataFrame
- Python Pandas - Plot multiple data columns in a DataFrame?
- Python Pandas - Query the columns of a DataFrame
- Python - Select multiple columns from a Pandas dataframe
- Python Pandas – Count the rows and columns in a DataFrame
- Python Pandas – Get the datatype and DataFrame columns information
- Select multiple columns in a Pandas DataFrame
- Correlation between two numeric columns in a Pandas DataFrame
- Python Pandas - Filtering columns from a DataFrame on the basis of sum
- Plot multiple columns of Pandas DataFrame using Seaborn
- Python Pandas - Create a DataFrame with the levels of the MultiIndex as columns
- How to find the standard deviation of specific columns in a dataframe in Pandas Python?
- How to change the order of Pandas DataFrame columns?
- How to sort multiple columns of a Pandas DataFrame?

Advertisements