Home »
Python »
Python Programs
Count the frequency that a value occurs in a DataFrame column
Given a DataFrame, we need to count the frequency values in a particular column.
Submitted by Pranit Sharma, on April 28, 2022
Problem statement
Given a DataFrame, we need to count the frequency values in a particular column.
Counting the frequency that a value occurs in a DataFrame column
In pandas, we can count the frequency of a particular column using DataFrame.value_count() method. This method is used to calculate the frequency of all values in a column separately. It takes the column name inside it as a parameter and returns a series of all the values with their respective frequencies. The important point is the that the returned series is descending in nature i.e., the value having highest frequency would be the first element of the series.
Syntax
DataFrame.value_counts(
subset=None,
normalize=False,
sort=True,
ascending=False,
dropna=True
)
# or
DataFrame.value_counts(["col_name"])
Note
To work with pandas, we need to import pandas package first, below is the syntax:
import pandas as pd
Let us understand with the help of an example.
Python program to count the frequency that a value occurs in a DataFrame column
# Importing pandas package
import pandas as pd
# Creating a dictionary
dict = {
'Name':['Harry','Raman','Parth','Mukesh','Neelam','Megha','Deepak','Nitin','Manoj','Rishi','Sandeep','Divyansh','Sheetal','Shalini'],
'Sport_selected':['Cricket','Cricket','Cricket','Cricket','Basketball','Basketball','Football','Cricket','Tennis','Tennis','Chess','Football','Basketball','Chess']
}
# Creating a DataFrame
df=pd.DataFrame(dict)
# Display original DataFrame
print("Original DataFrame:\n",df,"\n")
# Counting frequency of column named Sport_selected
frequency_of_sports = df['Sport_selected'].value_counts()
# Display all the frequencies
print("Frequency of sports is:\n",frequency_of_sports,"\n")
Output
The output of the above program is:
Python Pandas Programs »