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 b0 0 no M1 1 yes F2 1 yes M3 1 no F4 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 30 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_dftarget a b0 0 no M4 0 no F>>> len(sub_df)2
