0
0
NumPydata~20 mins

np.unique() for unique elements in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
np.unique Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A(array([1, 2, 3, 4]), array([2, 1, 2, 2]))
B(array([1, 2, 3, 4]), array([1, 2, 2, 2]))
C(array([1, 2, 3, 4]), array([2, 2, 2, 1]))
D(array([1, 2, 3, 4]), array([1, 1, 1, 1]))
Attempts:
2 left
💡 Hint
Think about how many times each unique number appears in the array.
data_output
intermediate
1: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))
A6
B4
C7
D5
Attempts:
2 left
💡 Hint
Count each distinct number in the whole 2D array.
Predict Output
advanced
2: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)
A[2 3 5] [3 1 0] [2 1 2 0 1]
B]1 2 0 1 0[ ]0 1 3[ ]5 3 2[
C[2 3 5] [3 1 0] [0 1 0 2 1]
D[2 3 5] [3 1 0] [0 1 2 0 1]
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.
🔧 Debug
advanced
1: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)
AValueError: invalid literal for int() with base 10: 'yes'
BTypeError: return_counts must be a boolean
CTypeError: 'str' object cannot be interpreted as an integer
DTypeError: return_counts must be a bool
Attempts:
2 left
💡 Hint
Check the expected type for the return_counts parameter.
🚀 Application
expert
3: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?
A
unique, counts = np.unique(arr, return_counts=True)
duplicates = unique[counts > 1]
B
unique = np.unique(arr)
duplicates = [x for x in unique if arr.count(x) > 1]
Cduplicates = np.unique(arr[arr > 1])
D
unique, counts = np.unique(arr)
duplicates = unique[counts > 1]
Attempts:
2 left
💡 Hint
Use return_counts to get counts of each unique element.