Count the frequency of a value in a DataFrame column in Pandas



To count the frequency of a value in a DataFrame column in Pandas, we can use df.groupby(column name).size() method.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print the input DataFrame, df.

  • Print frequency of column, x.

  • Print frequency of column, y.

  • Print frequency of column, z.

Example

 Live Demo

import pandas as pd df = pd.DataFrame(    {       "x": [5, 2, 1, 5],       "y": [4, 10, 5, 10],       "z": [1, 1, 5, 1]    } ) print "Input DataFrame is:
", df col = "x" count = df.groupby('x').size() print "Frequency of values in column ", col, "is:
", count col = "y" count = df.groupby('y').size() print "Frequency of values in column ", col, "is:
", count col = "z" count = df.groupby('z').size() print "Frequency of values in column ", col, "is:
", count

Output

Input DataFrame is:    x  y  z 0  5  4  1 1  2 10  1 2  1  5  5 3 5  10  1 Frequency of values in column x is:    x 1  1 2  1 5  2 dtype: int64 Frequency of values in column y is:    y 4  1 5  1 10 2 dtype: int64 Frequency of values in column z is:    z 1  3 5  1 dtype: int64
Updated on: 2021-08-30T12:13:18+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements