- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements