Challenge - 5 Problems
np.unique Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of np.unique() with return_counts
What is the output of this code snippet using
np.unique() with return_counts=true?NumPy
import numpy as np arr = np.array([3, 1, 2, 3, 2, 1, 4]) result = np.unique(arr, return_counts=True) print(result)
Attempts:
2 left
💡 Hint
Think about how many times each unique number appears in the array.
✗ Incorrect
The array contains 1 twice, 2 twice, 3 twice, and 4 once. np.unique returns sorted unique elements and their counts.
❓ data_output
intermediate1:30remaining
Number of unique elements in a 2D array
How many unique elements are in this 2D numpy array?
NumPy
import numpy as np arr = np.array([[1, 2, 2], [3, 1, 4], [4, 5, 5]]) unique_elements = np.unique(arr) print(len(unique_elements))
Attempts:
2 left
💡 Hint
Count each distinct number in the whole 2D array.
✗ Incorrect
The unique elements are 1, 2, 3, 4, 5, so total 5 unique elements. But check carefully if any number repeats or is missed.
❓ Predict Output
advanced2:30remaining
Output of np.unique() with return_index and return_inverse
What is the output of this code using
np.unique() with return_index=true and return_inverse=true?NumPy
import numpy as np arr = np.array([5, 3, 5, 2, 3]) unique, index, inverse = np.unique(arr, return_index=True, return_inverse=True) print(unique, index, inverse)
Attempts:
2 left
💡 Hint
Remember that
return_index gives the first occurrence index of each unique element, and return_inverse maps original elements to unique indices.✗ Incorrect
Unique sorted elements are [2, 3, 5]. Their first indices in arr are 3 for 2, 1 for 3, and 0 for 5. The inverse array maps each element in arr to the index in unique.
🔧 Debug
advanced1:30remaining
Identify the error in np.unique() usage
What error will this code raise?
NumPy
import numpy as np arr = np.array([1, 2, 3]) result = np.unique(arr, return_counts='yes') print(result)
Attempts:
2 left
💡 Hint
Check the expected type for the return_counts parameter.
✗ Incorrect
The parameter return_counts expects a boolean value true or false, not a string. Passing 'yes' causes a TypeError.
🚀 Application
expert3:00remaining
Using np.unique() to find duplicates in a large dataset
You have a large numpy array of integers. Which code snippet correctly identifies all elements that appear more than once?
Attempts:
2 left
💡 Hint
Use return_counts to get counts of each unique element.
✗ Incorrect
Option A correctly uses np.unique with return_counts=true to get counts, then filters unique elements with counts greater than 1. Option A uses list method count which does not work on numpy arrays. Option A filters by value > 1, not duplicates. Option A tries to unpack np.unique without return_counts, causing error.