Pandas value_counts(): Count Unique Values in a DataFrame
The Pandas value_counts() method counts how many times each distinct value appears in a Series. It is especially useful for analysing categories such as product types, customer segments, survey responses, grades, departments and transaction statuses.
In this tutorial, you will learn how to use value_counts() in Pandas, count categories in a DataFrame column, calculate proportions and percentages, include missing values, control sorting, count combinations of columns, and interpret the results. Examples use practical data and can be run in Jupyter Notebook or a Python script.
If you are new to Pandas, start with the Pandas DataFrame guide or learn how to select rows and columns, filter rows and group data with groupby().
- What does value_counts() do?
- Create a sample DataFrame
- Count values in one column
- Sort counts and change the order
- Calculate proportions and percentages
- Count missing values
- Return the most common values
- Count combinations of columns
- Series versus DataFrame
- Useful parameters and options
- Business examples
- Common mistakes
- Practice exercises with solutions
- Frequently asked questions
1. What Does Pandas value_counts() Do?
value_counts() returns a frequency table: each unique value is listed alongside the number of times it occurs. By default, results are ordered from the most frequent value to the least frequent value, and missing values are excluded.
The method is normally called on a Series, which is often a single DataFrame column:
df["Department"].value_counts()
This is different from count(), which counts non-missing entries overall, and nunique(), which returns the number of distinct values rather than a count for every category.
| Method | What it returns | Example question |
|---|---|---|
value_counts() | Frequency of each distinct value | How many orders are in each status? |
count() | Number of non-missing entries | How many orders have a recorded status? |
nunique() | Number of distinct non-missing values by default | How many different statuses occur? |
2. Create a Sample DataFrame
We will use a small retail order dataset. The Status, Category and Region columns will help demonstrate frequency counts.
import pandas as pd
orders = pd.DataFrame({
"OrderID": [101, 102, 103, 104, 105, 106, 107, 108, 109, 110],
"Category": ["Laptop", "Phone", "Phone", "Accessory", "Laptop",
"Phone", "Accessory", "Laptop", "Phone", "Accessory"],
"Status": ["Delivered", "Pending", "Delivered", "Cancelled", "Delivered",
"Pending", "Delivered", "Pending", "Delivered", None],
"Region": ["North", "South", "North", "West", "East",
"South", "East", "North", "West", "South"]
})
print(orders)
OrderID Category Status Region 0 101 Laptop Delivered North 1 102 Phone Pending South 2 103 Phone Delivered North 3 104 Accessory Cancelled West 4 105 Laptop Delivered East 5 106 Phone Pending South 6 107 Accessory Delivered East 7 108 Laptop Pending North 8 109 Phone Delivered West 9 110 Accessory None South
In real projects, you may first load a file with read_csv() or read_excel(), then use value_counts() to inspect the columns.
3. Count Values in One Column
To count each order status, select the Status column and call value_counts().
status_counts = orders["Status"].value_counts()
print(status_counts)
Status Delivered 5 Pending 3 Cancelled 1 Name: count, dtype: int64
The result is a Pandas Series. Its index contains the distinct status labels, and its values contain their frequencies. There are five delivered orders, three pending orders and one cancelled order. The row with a missing status is not counted by default.
orders["Status"].value_counts() for a single column. Writing orders.value_counts() counts unique combinations of entire rows, which is a different operation.4. Sort Counts and Change the Order
By default, value_counts() sorts by frequency in descending order. Set ascending=True to put the least frequent values first.
orders["Category"].value_counts(ascending=True)
Category Laptop 3 Accessory 3 Phone 4 Name: count, dtype: int64
When categories have equal counts, their relative order should not be relied on unless you explicitly sort the result. You can sort by the category label after counting:
category_counts = orders["Category"].value_counts()
category_counts = category_counts.sort_index()
print(category_counts)
Category Accessory 3 Laptop 3 Phone 4 Name: count, dtype: int64
Use sort_values() to order by the counts, or sort_index() to order by the category labels. Read the Pandas sort_values() tutorial for more details.
5. Calculate Proportions and Percentages
For reports and dashboards, counts alone may not be enough. Pass normalize=True to return the proportion of non-missing values represented by each category. Multiply by 100 to convert proportions into percentages.
status_share = orders["Status"].value_counts(normalize=True)
print(status_share.round(3))
status_percent = orders["Status"].value_counts(normalize=True) * 100
print(status_percent.round(1))
Status Delivered 0.556 Pending 0.333 Cancelled 0.111 Name: proportion, dtype: float64 Status Delivered 55.6 Pending 33.3 Cancelled 11.1 Name: proportion, dtype: float64
There are nine recorded statuses, so the percentages are calculated out of nine rather than all ten rows. Missing values are excluded unless you set dropna=False. Rounded percentages may add to 99.9% or 100.1% because of rounding.
You can format the output for a report:
percent = orders["Status"].value_counts(normalize=True).mul(100).round(1)
print(percent.astype(str) + "%")
6. Count Missing Values
By default, value_counts() excludes missing values such as None, NaN and pd.NA. To show the missing category in the result, use dropna=False.
print(orders["Status"].value_counts(dropna=False))
Status Delivered 5 Pending 3 Cancelled 1 NaN 1 Name: count, dtype: int64
This is helpful when checking data quality. If your goal is specifically to count missing entries, use orders["Status"].isna().sum(). To count non-missing entries, use orders["Status"].count().
For a full guide to cleaning null values, see handling missing values in Pandas.
7. Return the Most Common Values
Use head(n) after value_counts() to return the top n categories. This is useful for identifying best-selling products, common support issues or the most frequent survey answers.
top_two_categories = orders["Category"].value_counts().head(2)
print(top_two_categories)
Category Phone 4 Laptop 3 Name: count, dtype: int64
If you want only categories that occur at least three times, filter the resulting Series:
counts = orders["Category"].value_counts()
print(counts[counts >= 3])
Note that head(2) returns two entries, while counts >= 3 returns every category whose frequency meets the threshold.
8. Count Combinations of Columns
Sometimes the question involves more than one field, such as the number of orders for each combination of region and status. You can use value_counts() on a selection of multiple columns.
region_status_counts = orders[["Region", "Status"]].value_counts(dropna=False)
print(region_status_counts)
The result is a Series with a MultiIndex: one index level for each selected column. It shows how often each combination occurs. The exact ordering is based on the count unless you request ascending order.
For a table with one category per row and combinations spread across columns, use groupby() or a pivot table. For example:
status_by_region = orders.groupby(["Region", "Status"], dropna=False).size()
print(status_by_region)
Learn more in the Pandas groupby() tutorial.
9. Series Versus DataFrame value_counts()
It is important to understand which object you are counting:
df["column"].value_counts()counts the distinct values in one column.df[["A", "B"]].value_counts()counts the distinct combinations of values across the selected columns.df.value_counts()counts distinct combinations across all columns of the DataFrame.
For example, if two rows have the same category and region, counting both columns together gives that combination a count of two. It does not separately count the frequency of each category and each region.
10. Useful Parameters and Options
| Parameter or method | Purpose | Example |
|---|---|---|
normalize=True | Return proportions rather than raw frequencies | s.value_counts(normalize=True) |
sort=False | Do not sort results by frequency | s.value_counts(sort=False) |
ascending=True | Sort by count from low to high | s.value_counts(ascending=True) |
dropna=False | Include a missing-value entry | s.value_counts(dropna=False) |
bins=... | Count numeric values in intervals | s.value_counts(bins=4) |
head(n) | Keep the first n results | s.value_counts().head(5) |
sort_index() | Sort the resulting index labels | s.value_counts().sort_index() |
Count numeric values in bins
For continuous numeric data such as age or transaction amount, counting every exact value may not be useful. The bins parameter groups numeric values into intervals:
ages = pd.Series([18, 21, 22, 25, 31, 34, 37, 42, 48, 51])
print(ages.value_counts(bins=4, sort=False))
This is a quick way to inspect a distribution. If you need custom interval boundaries or labelled groups, consider pd.cut() and then use value_counts() on the resulting categories.
11. Practical Business Examples
Example A: Count customer segments
customers = pd.DataFrame({
"CustomerID": [1, 2, 3, 4, 5, 6],
"Segment": ["New", "Returning", "Returning", "New", "VIP", "Returning"]
})
print(customers["Segment"].value_counts())
This shows how many customers fall into each segment and can support a simple customer profile.
Example B: Analyse survey answers as percentages
survey = pd.Series(["Satisfied", "Neutral", "Satisfied", "Dissatisfied", "Satisfied", "Neutral"])
response_percent = survey.value_counts(normalize=True).mul(100).round(1)
print(response_percent)
Percentages make it easier to compare groups of different sizes. Always state whether missing responses were included in the denominator.
Example C: Identify common product categories
print(orders["Category"].value_counts().head(3))
This quickly identifies the categories appearing most frequently in the sample orders. Frequency is not the same as revenue: to analyse sales value, calculate or aggregate revenue separately.
12. Common Mistakes and How to Fix Them
Mistake 1: Calling value_counts() on a column name string
"Status".value_counts() will not count values in your DataFrame because it is a string, not the column Series. Use df["Status"].value_counts().
Mistake 2: Expecting missing values to be included
Missing entries are excluded by default. Set dropna=False when they should appear in the frequency table.
Mistake 3: Confusing counts with percentages
Use normalize=True for proportions. Multiply the result by 100 for percentages.
Mistake 4: Counting all rows instead of one column
df.value_counts() counts distinct row combinations. To count the categories in a column, select that column first.
Mistake 5: Assuming the result is a DataFrame
For a single Series, value_counts() returns a Series. Use reset_index() if you need a DataFrame for further processing or export.
counts_df = orders["Category"].value_counts().rename_axis("Category").reset_index(name="Count")
print(counts_df)
13. Practice Exercises with Solutions
Try to solve each task before looking at the suggested solution. Use the orders DataFrame defined earlier.
Exercise 1: Count each region
Write code to count the orders from each region.
Show solution
orders["Region"].value_counts()
Exercise 2: Include missing order statuses
Count every status, including missing values.
Show solution
orders["Status"].value_counts(dropna=False)
Exercise 3: Calculate category percentages
Find what percentage of the rows belongs to each product category.
Show solution
orders["Category"].value_counts(normalize=True).mul(100).round(1)
Exercise 4: Find the two most common categories
Show solution
orders["Category"].value_counts().head(2)
Exercise 5: Count combinations of region and category
Show solution
orders[["Region", "Category"]].value_counts()
14. Frequently Asked Questions
What does value_counts() do in Pandas?
It counts the frequency of each distinct value in a Series. It is commonly used to summarise categorical data and inspect the distribution of values.
How do I use value_counts() on a DataFrame column?
Select the column and call the method, for example df["Category"].value_counts().
How do I get percentages instead of counts?
Use df["Category"].value_counts(normalize=True) * 100. The default denominator excludes missing values.
How do I include NaN values in value_counts()?
Use df["Category"].value_counts(dropna=False) to include missing values in the output.
How do I find the most frequent value?
Use df["Category"].value_counts().head(1). This returns the most frequent category and its count. If multiple values are tied, inspect the returned results rather than assuming there is a unique winner.
What is the difference between value_counts() and groupby().size()?
value_counts() is a concise way to count distinct values or combinations. groupby().size() groups rows by one or more keys and counts rows in each group, offering more flexibility for multi-step analysis.
Does value_counts() change my original DataFrame?
No. It returns a new Series of counts or proportions and does not modify the original DataFrame.
How do I turn value_counts() into a DataFrame?
Use df["Category"].value_counts().rename_axis("Category").reset_index(name="Count") to create a two-column DataFrame containing category labels and counts.
Related Pandas Tutorials
- Python Pandas Tutorial: Complete Guide
- Introduction to Pandas
- Pandas DataFrame
- Read CSV Files with Pandas
- Select Rows and Columns in Pandas
- Filter a Pandas DataFrame
- Sort a Pandas DataFrame
- Pandas groupby()
- Handle Missing Values in Pandas
Next: Learn how to load data from CSV files with Pandas read_csv().
