Home » Pandas: How to Get Frequency Counts of Values in Column

Pandas: How to Get Frequency Counts of Values in Column

by Tutor Aspire

You can use the following methods to get frequency counts of values in a column of a pandas DataFrame:

Method 1: Get Frequency Count of Values in Table Format

df['my_column'].value_counts()

Method 2: Get Frequency Count of Values in Dictionary Format

df['my_column'].value_counts().to_dict()

The following examples shows how to use each method in practice with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'C'],
                   'points': [12, 20, 25, 8, 12, 19, 27, 35]})

#view DataFrame
print(df)

  team  points
0    A      12
1    A      20
2    A      25
3    A       8
4    B      12
5    B      19
6    B      27
7    C      35

Example 1: Get Frequency Count of Values in Table Format

We can use the value_counts() function to get a frequency count of each unique value in the team column of the DataFrame and display the results in a table format:

#get frequency count of values in 'team' column
df['team'].value_counts()

A    4
B    3
C    1
Name: team, dtype: int64

From the results we can see:

  • The value ‘A’ occurs 4 times in the team column.
  • The value ‘B’ occurs 3 times in the team column.
  • The value ‘C’ occurs 1 time in the team column.

Notice that the results are displayed in a table format.

Example 2: Get Frequency Count of Values in Dictionary Format

We can use the value_counts() function and the to_dict() function to get a frequency count of each unique value in the team column of the DataFrame and display the results in a dictionary format:

#get frequency count of values in 'team' column and display in dictionary
df['team'].value_counts().to_dict()

{'A': 4, 'B': 3, 'C': 1}

The frequency counts of each unique value in the team column are shown in a dictionary format.

For example, we can see:

  • The value ‘A’ occurs 4 times in the team column.
  • The value ‘B’ occurs 3 times in the team column.
  • The value ‘C’ occurs 1 time in the team column.

This matches the frequency counts in the previous method.

The results are simply shown in a different format.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

Pandas: How to Use GroupBy and Value Counts
Pandas: How to Use GroupBy with Bin Counts
Pandas: How to Count Values in Column with Condition

You may also like