np.unique lists distinct values (sorted). Integer codes (0 = Nairobi, …) let bincount tally without string columns.
Goal
Count distinct values, return counts, and use bincount on city ids.
Unique
products = np.array([0, 1, 0, 0, 1, 2, 0, 1])
print(np.unique(products))
values, counts = np.unique(products, return_counts=True)
print("values:", values)
print("counts:", counts)0, 1, 2 are products A, B, C. unique always sorts.
City ids
# 0 Nairobi, 1 Mombasa, 2 Kisumu, 3 Nakuru, 4 Eldoret
city = np.array([0, 0, 1, 1, 2, 0, 3, 4, 1, 2])
print(np.unique(city, return_counts=True))bincount
city = np.array([0, 0, 1, 1, 2, 0, 3, 4, 1, 2])
print(np.bincount(city))Index i is the count for city id i. Missing ids in the middle still get a 0 if a larger id exists.
Weighted bincount
city = np.array([0, 0, 1, 2, 0])
units = np.array([12, 7, 9, 3, 5], dtype=float)
print(np.bincount(city, weights=units))Nairobi (id 0) sold 12+7+5 = 24 units across those rows.
Tip
Keep names in comments. Integer codes are the join key for bincount and for stacking later.