Pandas value_counts Function: Usage, Examples, & Use Cases

This tutorial provides a detailed guide on using Pandas' value_counts function to count unique values, & integrate results with DataFrames for deeper insights.

Understanding the distribution and frequency of data is crucial for any data analysis task, and Pandas provides the value_counts function for this purpose:  Whether you're dealing with a simple list of items or a complex DataFrame, value_counts allows you to quickly and easily count the occurrences of unique values. This tutorial will guide you through the various usages and capabilities of the value_counts function, complete with practical examples and additional use cases. From fundamental frequency counts to advanced applications like handling missing values and combining results with DataFrames, you'll learn how to leverage this function to gain meaningful insights from your data.

What is value_counts in Pandas? 

value_counts is a function in the Pandas library that counts the frequency of unique values in a Series or DataFrame column. It returns a Series containing counts of unique values. This function is beneficial for data analysis and preprocessing tasks, providing insights into the distribution of categorical data.

Example of Basic Usage of Pandas value_counts Function 

Let’s take a look at the example below that shows the usage of the value_counts function in Pandas using a step-by-step process - 

Step 1 - Import Library

import pandas as pd

Step 2 - Take Sample data

Sample_data = pd.Series(['India','USA','Canada','UK','Japan','India','USA','USA','Canada','UK','UK','Japan','India','India','India','India'])

Step 3 - Print Results

print("This is Resulted output for value_counts function in pandas:","\n",Sample_data.value_counts())

 

This results output for the value_counts function in pandas: 

India     6

USA       3

UK        3

Japan     2

Canada    2

dtype: int64

 

How to Count Specific Values in a Column Using Pandas value_counts Function?

You can apply the value_counts function directly to the column of interest to count specific values in a column. Let's consider a DataFrame for this example:

 

Pandas count specific value in column using value_counts

 

 

This counts the occurrences of each country in the "Country" column of the DataFrame. 

How to Use value_counts with Multiple Columns Using Pandas? 

Pandas' value_counts function can be combined with other functions to count unique values across multiple columns. For example, using the apply method with a lambda function

 

Pandas value counts multiple columns

 

This counts unique values in the "Country" and "City" columns, displaying a DataFrame with counts of unique entries for each column.

Additional Example 1: Calculating value_counts as Percentage 

Use the normalize=True parameter to calculate the frequency counts as percentages - 

 

Pandas value counts as a percentage

 

This output shows the relative frequency of each unique value as a proportion of the total number of values. 

Additional Example 2: Sorting value_counts by Index  

Use the sort_index method to sort the counts by the index (i.e., alphabetically by country name). 

 

Sorting value counts by index

 

This output shows the frequency counts sorted by the country names in alphabetical order. 

Additional Use Cases on Pandas value_counts function 

 

  1. Filtering Value Counts - You can filter the value counts to include only those with counts above a certain threshold. You can achieve this by chaining conditions with value_counts.

 

Using value_counts in Pandas for Filtering

 

This output shows only the countries that appear more than twice in the DataFrame.

  1. Combining Value Counts with DataFrame: The map function can add the value counts as a new column in the original DataFrame. 

Combining value_counts with DataFrame

 

This DataFrame now includes a Country_Counts column showing the count of each country.

  1. Counting Values in a DataFrame: You can also use value_counts to count values in the entire DataFrame by flattening it into a single Series using pd.Series and stack. 

Counting values in a Dataframe

 

This counts all occurrences of each value in the entire DataFrame, regardless of the column. 

Master Pandas value_counts Function with ProjectPro! 

This tutorial has demonstrated various ways to leverage value_counts to count unique values, handle missing data, and integrate results within DataFrames. Gaining practical experience through real-world projects is indispensable to excel in using these techniques. ProjectPro can be your gateway to this hands-on learning. With over 270+ projects focused on data science and big data, ProjectPro offers you the chance to apply what you've learned in this tutorial to real-world scenarios, solidifying your skills and enhancing your data analysis capabilities.

What Users are saying..

profile image

Jingwei Li

Graduate Research assistance at Stony Brook University
linkedin profile url

ProjectPro is an awesome platform that helps me learn much hands-on industrial experience with a step-by-step walkthrough of projects. There are two primary paths to learn: Data Science and Big Data.... Read More

Relevant Projects

PyCaret Project to Build and Deploy an ML App using Streamlit
In this PyCaret Project, you will build a customer segmentation model with PyCaret and deploy the machine learning application using Streamlit.

Recommender System Machine Learning Project for Beginners-3
Content Based Recommender System Project - Building a Content-Based Product Recommender App with Streamlit

Build a Hybrid Recommender System in Python using LightFM
In this Recommender System project, you will build a hybrid recommender system in Python using LightFM .

Model Deployment on GCP using Streamlit for Resume Parsing
Perform model deployment on GCP for resume parsing model using Streamlit App.

Autogen Project to Build an Intelligent AI Personal Assistant
Build a multi-agent AI personal assistant using Autogen that can handle tasks like managing calendars, emails, reminders, messaging, research, and weather updates, automating everyday workflows with LLMs and tool integrations. This is an upcoming project that is expected to be launched in June.

Learn to Build a Neural network from Scratch using NumPy
In this deep learning project, you will learn to build a neural network from scratch using NumPy

NLP Project for Multi Class Text Classification using BERT Model
In this NLP Project, you will learn how to build a multi-class text classification model using using the pre-trained BERT model.

Create Your First Chatbot with RASA NLU Model and Python
Learn the basic aspects of chatbot development and open source conversational AI RASA to create a simple AI powered chatbot on your own.

Personalized Medicine: Redefining Cancer Treatment
In this Personalized Medicine Machine Learning Project you will learn to classify genetic mutations on the basis of medical literature into 9 classes.

Avocado Machine Learning Project Python for Price Prediction
In this ML Project, you will use the Avocado dataset to build a machine learning model to predict the average price of avocado which is continuous in nature based on region and varieties of avocado.

OSZAR »