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

PandasServer Side ProgrammingProgramming

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:\n", df
col = "x"
count = df.groupby('x').size()
print "Frequency of values in column ", col, "is:\n", count

col = "y"
count = df.groupby('y').size()
print "Frequency of values in column ", col, "is:\n", count

col = "z"
count = df.groupby('z').size()
print "Frequency of values in column ", col, "is:\n", 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
raja
Published on 30-Aug-2021 12:12:29
Advertisements