Pandas GroupBy – Count the occurrences of each combination

PythonServer Side ProgrammingProgrammingPandas

To groupby columns and count the occurrences of each combination in Pandas, we use the DataFrame.groupby() with size(). The groupby() method separates the DataFrame into groups.

At first, let us import the pandas library with an alias pd −

import pandas as pd

Initialize the data of lists −

# initializing the data
mylist = {'Car': ['BMW', 'Mercedes', 'Lamborgini', 'Audi', 'Mercedes', 'Porche', 'RollsRoyce', 'BMW'], 'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Bangalore', 'Hyderabad', 'Mumbai', 'Mumbai','Delhi'],
'Sold': [95, 80, 80, 75, 90, 90, 95, 50 ]}

Next, we will create a DataFrame −

# DataFrame
dataFrame = pd.DataFrame(mylist, columns=['Car', 'Place', 'Sold'])

Now, use the groupby() to count the occurrence with the size() −

print("Counting the occurrences...")
res = dataFrame.groupby(['Car', 'Place']).size()

Following is the code to count the occurrences of each combination −

Example

# importing library
import pandas as pd

# initializing the data
mylist = {'Car': ['BMW', 'Mercedes', 'Lamborgini', 'Audi', 'Mercedes', 'Porsche', 'RollsRoyce', 'BMW'],
'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Bangalore', 'Hyderabad', 'Mumbai', 'Mumbai','Delhi'],
'Sold': [95, 80, 80, 75, 90, 90, 95, 50 ]}

# DataFrame
dataFrame = pd.DataFrame(mylist, columns=['Car', 'Place', 'Sold'])

print(dataFrame)

print("Counting the occurrences...")
res = dataFrame.groupby(['Car', 'Place']).size()

# Displaying the occurrences
print(res)

Output

This will produce the following output −

          Car           Place       Sold
0         BMW           Delhi         95
1    Mercedes       Hyderabad         80
2  Lamborgini      Chandigarh         80
3        Audi       Bangalore         75
4    Mercedes       Hyderabad         90
5     Porsche          Mumbai         90
6  RollsRoyce          Mumbai         95
7         BMW           Delhi         50
Counting the occurrences...
Car         Place
Audi        Bangalore     1
BMW         Delhi         2
Lamborgini  Chandigarh    1
Mercedes    Hyderabad     2
Porsche     Mumbai        1
RollsRoyce  Mumbai        1
dtype: int64
raja
Published on 07-Sep-2021 09:09:30
Advertisements