We use np.unique() to find all the different values in a list or array. It helps us see what unique items are there without repeats.
np.unique() for unique elements in NumPy
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
NumPy
np.unique(array, return_index=False, return_inverse=False, return_counts=False, axis=None)
array is the input list or array you want to check.
Optional arguments let you get extra info like where each unique item first appears (return_index) or how many times each appears (return_counts).
Examples
NumPy
import numpy as np arr = np.array([1, 2, 2, 3, 4, 4, 4]) unique_values = np.unique(arr) print(unique_values)
NumPy
unique_vals, counts = np.unique(arr, return_counts=True) print(unique_vals) print(counts)
NumPy
arr2d = np.array([[1, 2], [2, 3]]) unique_rows = np.unique(arr2d, axis=0) print(unique_rows)
Sample Program
This program shows how to find unique numbers in a list and count how many times each appears.
NumPy
import numpy as np # Create an array with repeated numbers numbers = np.array([5, 3, 5, 2, 3, 8, 9, 2, 8]) # Find unique numbers unique_numbers = np.unique(numbers) print('Unique numbers:', unique_numbers) # Find unique numbers and their counts unique_vals, counts = np.unique(numbers, return_counts=True) print('Counts of each unique number:') for val, count in zip(unique_vals, counts): print(f'{val} appears {count} times')
Important Notes
np.unique() returns sorted unique values by default.
Use return_counts=True to see how often each unique value appears.
For 2D arrays, use axis=0 or axis=1 to find unique rows or columns.
Summary
np.unique() helps find all different values in data.
It can also tell you how many times each unique value appears.
Works with 1D and 2D arrays, and sorts the results automatically.
Practice
1. What does the
np.unique() function do when applied to a NumPy array?easy
Solution
Step 1: Understand the purpose of np.unique()
The functionnp.unique()extracts all different values from the input array and sorts them.Step 2: Compare with other options
Options A, B, and D describe different functions like shape, sum, and max, which are not whatnp.unique()does.Final Answer:
Returns all unique elements sorted from the array -> Option DQuick Check:
np.unique() = unique sorted elements [OK]
Hint: np.unique() always returns sorted unique values [OK]
Common Mistakes:
- Thinking it returns counts by default
- Confusing with sum or max functions
- Assuming it returns unsorted unique values
2. Which of the following is the correct syntax to get unique elements from a NumPy array
arr?easy
Solution
Step 1: Recall the correct function call
The correct way to call the unique function in NumPy isnp.unique(arr).Step 2: Identify incorrect syntax
Options A, B, and C are invalid because either the method does not exist on the array object or the function is not called from the NumPy module correctly.Final Answer:
np.unique(arr) -> Option AQuick Check:
Use np.unique(array) syntax [OK]
Hint: Always call unique as np.unique(array) [OK]
Common Mistakes:
- Trying to call unique as a method on array
- Forgetting the np. prefix
- Using a non-existent unique() function without np
3. What is the output of the following code?
import numpy as np arr = np.array([3, 1, 2, 3, 2, 1, 4]) result = np.unique(arr) print(result)
medium
Solution
Step 1: Apply np.unique() to the array
The function extracts unique values from the array: 1, 2, 3, and 4.Step 2: Note the sorting behavior
np.unique() returns these unique values sorted in ascending order: [1 2 3 4].Final Answer:
[1 2 3 4] -> Option CQuick Check:
Unique sorted values = [1 2 3 4] [OK]
Hint: np.unique() sorts unique values automatically [OK]
Common Mistakes:
- Expecting original order instead of sorted
- Including duplicates in output
- Confusing with counts output
4. The following code is intended to print unique elements of
arr but raises an error. What is the error?import numpy as np arr = np.array([5, 6, 5, 7]) result = arr.unique() print(result)
medium
Solution
Step 1: Identify the method call on the array
The code callsarr.unique(), but NumPy arrays do not have a method namedunique().Step 2: Understand the correct usage
The correct function isnp.unique(arr), a function in the NumPy module, not a method of the array object.Final Answer:
'numpy.ndarray' object has no attribute 'unique' -> Option AQuick Check:
Arrays have no unique() method [OK]
Hint: np.unique() is a function, not an array method [OK]
Common Mistakes:
- Calling unique() as a method on array
- Forgetting to import numpy as np
- Using wrong function name or syntax
5. Given a 2D NumPy array
arr = np.array([[1, 2, 2], [3, 1, 4]]), which code correctly finds all unique elements in the entire array?hard
Solution
Step 1: Understand np.unique() on 2D arrays
Callingnp.unique(arr)flattens the array and returns all unique elements sorted.Step 2: Check axis parameter effects
Usingaxis=0oraxis=1returns unique rows or columns, not unique elements overall.Step 3: Identify invalid method call
arr.unique()is invalid because arrays do not have a unique method.Final Answer:
np.unique(arr) -> Option BQuick Check:
np.unique(array) finds all unique elements [OK]
Hint: Use np.unique(arr) to get all unique elements in any array [OK]
Common Mistakes:
- Using axis parameter expecting unique elements, but it returns unique rows/columns
- Calling unique() as a method on array
- Confusing unique elements with unique rows or columns
