Q:

Count the frequency that a value occurs in a DataFrame column

belongs to collection: Python Pandas Programs

0

pandas.DataFrame.value_counts() 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"])

To work with Python Pandas, we need to import the pandas library. Below is the syntax,

import pandas as pd

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Let us understand with the help of an example.

# 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:

Output | Count the frequency

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python Pandas: Get index of rows which column matc... >>
<< Sorting columns in pandas DataFrame based on colum...