Python Pandas – Count the Observations


To count the observations, first use the groupby() and then use count() on the result. At first, import the required library −

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

Group the column with duplicate values −

group = dataFrame.groupby("Product Category")

Get the count −

group.count()

Example

Following is the code −

import pandas as pd

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

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

# count the observations
group = dataFrame.groupby("Product Category")

print"\nResultant DataFrame...\n",group.count()

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

Resultant DataFrame...
                   Product Name   Quantity
Product Category
Computer                     2           2
Electronics                  2           2
Mobile Phone                 2           2

Updated on: 20-Sep-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements