Module 4 · Lesson 4
Unique Values & Counting
np.unique(arr) returns the sorted distinct values in an array. Pass
return_counts=True to also get how many times each value occurred, or
return_index=True to get the index of each value’s first occurrence.
Both are commonly used together with the unique values to build a simple
frequency table.
votes = np.array(["cat", "dog", "cat", "cat", "fox", "dog"])
values, counts = np.unique(votes, return_counts=True)
print("values:", values)
print("counts:", counts)
for value, count in zip(values, counts):
print(f"{value}: {count}")
Output:
values: ['cat' 'dog' 'fox']
counts: [3 2 1]
cat: 3
dog: 2
fox: 1
Most common value
Write most_common(arr) that returns the most frequently occurring value
in a 1-D array. Assume there's a unique winner (no ties to break).
💡 Hint
np.unique(arr, return_counts=True) gives you (values, counts) — find the index of the largest count with .argmax() and index into values.
✅ Solution
def most_common(arr):
values, counts = np.unique(arr, return_counts=True)
return values[counts.argmax()]
Values seen exactly once
Write singletons(arr) that returns, sorted, the values in a 1-D array
that occur exactly once.
💡 Hint
Get (values, counts) from np.unique(..., return_counts=True), then boolean-index values with counts == 1.
✅ Solution
def singletons(arr):
values, counts = np.unique(arr, return_counts=True)
return values[counts == 1]