Tsallaka zuwa abun ciki
Justice Tech School

Count Values

value_counts counts each distinct value. Use normalize=True for shares and unique or nunique for distinct values.

Example
import pandas as pd
import numpy as np
df = pd.DataFrame({'name': ['Ada', 'Bob', 'Cy', 'Di'], 'age': [30, 25, 35, 28], 'city': ['Lagos', 'Accra', 'Lagos', 'Nairobi'], 'score': [88.5, 92.0, 79.5, 85.0]})
print(df['city'].value_counts())
print(df['city'].value_counts(normalize=True).round(2).to_dict())
print(df['city'].nunique(), df['city'].unique().tolist())

Result

city
Lagos      2
Accra      1
Nairobi    1
Name: count, dtype: int64
{'Lagos': 0.5, 'Accra': 0.25, 'Nairobi': 0.25}
3 ['Lagos', 'Accra', 'Nairobi']

Exercise

Count distinct values.

df["city"].()

Quiz Test

What does normalize=True give?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.