Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Count the Number of Rows in Each Group using Python Pandas



Use the group.size() to count the number of rows in each group. Import the required library −

import pandas as pd

Create a DataFrame −

dataFrame = pd.DataFrame({'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'],'Quantity': [10, 50, 10, 20, 25, 50],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone']
})

Group by columns −

dataFrame.groupby(["Product Category", "Quantity"])

Now, count the group size to get the count of rows in each group.

Example

Following is the complete code −

import pandas as pd

# create a dataframe
dataFrame = pd.DataFrame({'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'],'Quantity': [10, 50, 10, 20, 25, 50],'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone']
})

# dataframe
print"Dataframe...\n",dataFrame

# grouping columns
new_group = dataFrame.groupby(["Product Category", "Quantity"])

# group size
new_group = new_group.size()

# dataframe
print"\nUpdated Dataframe...\n",new_group

Output

This will produce the following output −

Dataframe...
   Product Category   Product Name   Quantity
0          Computer       Keyboard         10
1      Mobile Phone        Charger         50
2       Electronics        SmartTV         10
3       Electronics         Camera         20
4          Computer   Graphic Card         25
5      Mobile Phone       Earphone         50

Updated Dataframe...
Product Category   Quantity
Computer           10        1
                   25        1
Electronics        10        1
                   20        1
Mobile Phone       50        2
dtype: int64
Updated on: 2021-09-20T08:05:51+05:30

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements