How to count the number of occurrences of elements in a pandas data frame column in python ?

How to count the number of occurrences of elements in a pandas data frame column in python ?

Daidalos April 15, 2020


Examples of how to count the number of occurrences of elements in a pandas data frame column in python

Create a simple date frame with pandas

Let's create a simple data frame called df:

>>> import pandas as pd
>>> import numpy as np

>>> df = pd.DataFrame(columns=['target','a','b'])

>>> df = df.append({"target": 0, "a":  "no", "b":  "M"}, ignore_index=True)
>>> df = df.append({"target": 1, "a":  "yes", "b":  "F"}, ignore_index=True)
>>> df = df.append({"target": 1, "a":  "yes", "b":  "M"}, ignore_index=True)
>>> df = df.append({"target": 1, "a":  "no", "b":  "F"}, ignore_index=True)
>>> df = df.append({"target": 0, "a":  "no", "b":  "F"}, ignore_index=True)

>>> df

returns

  target    a  b
0      0   no  M
1      1  yes  F
2      1  yes  M
3      1   no  F
4      0   no  F

Get the number of occurrences

To get the number of occurrences of elements in the column 'target', a solution is to use the function value_counts

>>> df['target'].value_counts()

returns

1    3
0    2

meaning value 1 (has 3 occurrences in the column) and 0 (has 2 occurrences in the column).

Another solution:

>>> sub_df = df[ df['target'] == 0 ]
>>>  sub_df 
  target   a  b
0      0  no  M
4      0  no  F
>>> len(sub_df) 
2

References

Links Site
How to get value counts for multiple columns at once in Pandas DataFrame? stackoverflow
get dataframe row count based on conditions stackoverflow
How to count occurrence of elements in a single column of Pandas Dataframe stackoverflow
pandas.Series.value_counts pandas doc
value_counts() Method: Count Unique Occurrences of Values in a Column