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?
NumPy
import numpy as np arr = np.array([3, 1, 2, 3, 2, 1, 4]) unique_vals, counts = np.unique(arr, return_counts=True) print(unique_vals) print(counts)
Attempts:
2 left
💡 Hint
np.unique() sorts the unique values by default.
✗ Incorrect
np.unique() returns sorted unique values. return_counts=True returns how many times each unique value appears in the original array.
❓ 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([[5, 2, 5], [3, 2, 1]]) unique_elements = np.unique(arr) print(len(unique_elements))
Attempts:
2 left
💡 Hint
Count all distinct numbers in the array.
✗ Incorrect
The unique elements are [1, 2, 3, 5]. There are 4 unique elements.
❓ Predict Output
advanced2:30remaining
Output of np.unique() with return_index and return_inverse
What will be printed by this code?
NumPy
import numpy as np arr = np.array([7, 2, 7, 3, 2]) unique_vals, indices, inverse = np.unique(arr, return_index=True, return_inverse=True) print(unique_vals) print(indices) print(inverse)
Attempts:
2 left
💡 Hint
return_index gives the first index of each unique value in the original array. return_inverse maps original elements to unique indices.
✗ Incorrect
unique_vals are sorted: [2, 3, 7]. Their first indices in arr are [1, 3, 0]. inverse maps each element in arr to its unique value index: arr[0]=7 -> 2, arr[1]=2 -> 0, etc.
❓ visualization
advanced3:00remaining
Visualizing unique values and their counts
Which option shows the correct bar chart for unique values and their counts from this array?
NumPy
import numpy as np import matplotlib.pyplot as plt arr = np.array([1, 2, 2, 3, 3, 3, 4]) unique_vals, counts = np.unique(arr, return_counts=True) plt.bar(unique_vals, counts) plt.xlabel('Unique Values') plt.ylabel('Counts') plt.title('Counts of Unique Values') plt.show()
Attempts:
2 left
💡 Hint
Count how many times each number appears in the array.
✗ Incorrect
The array has one '1', two '2's, three '3's, and one '4'. The bar heights match these counts.
🧠 Conceptual
expert3:00remaining
Effect of np.unique() on structured arrays
Given a structured numpy array with fields 'name' and 'age', what does np.unique() return by default?
NumPy
import numpy as np arr = np.array([('Alice', 25), ('Bob', 30), ('Alice', 25)], dtype=[('name', 'U10'), ('age', 'i4')]) unique_arr = np.unique(arr) print(unique_arr)
Attempts:
2 left
💡 Hint
np.unique() compares entire rows for structured arrays.
✗ Incorrect
np.unique() treats each row as a whole and returns unique rows. It does not extract individual fields unless specified.