Summarizing Values with np.unique
Introduction
Welcome back to Sorting, Unique Values, and Table Analysis with NumPy. We’re at lesson three of four in this course. In the last two lessons, we sorted values and ranked complete records while keeping each row intact. Now we’ll switch from ranking to summarizing: np.unique lists distinct values and counts their occurrences, and we can apply it to one column of a table.
By the end of this lesson, you’ll be able to:
- List the distinct values in a table with
np.unique - Count how often each value appears with
return_counts=True - Summarize a single column and check that the counts match the data
What np.unique Does to a Table
A table may contain many repeated values, but sometimes we only need to know which values appear. np.unique returns each distinct value once, in increasing order. When we give it a two-dimensional array, it considers values from the whole table together, rather than producing a separate list for each row or column. Here, codes is a 3 × 3 table of integer categories, and the print call asks for its distinct values.
The result contains 1, 2, and 3 once each. Repeated entries do not appear again:
Getting Values and Counts Together with return_counts=True
A list of distinct values tells us what appears, but not how often. Add return_counts=True to get both pieces of information. The call returns two arrays, so we unpack them into values and counts. This continues the same main() function and uses the table from the previous section; we are adding a summary, not changing how the table is built.
The values come back sorted in increasing order, and counts follows that same order, so the arrays line up by position: the first count belongs to the first value, the second count to the second value, and so on. For this table, the output is:
So 1 appears 3 times, 2 appears 4 times, and 3 appears 2 times. The two assert lines check this directly from the arrays we already have. An assert does nothing when its condition is True and raises an error when it is False, so these lines print nothing and leave our output unchanged. The first confirms that every distinct value has a count. The second confirms that the counts add up to codes.size, the 9 cells in the table, so no entry was missed or counted twice.
