Concept Flow - np.unique() for unique elements
Input array
Sort array
Find unique elements
Return unique array
np.unique() takes an array, sorts it, finds unique elements, and returns them as a new array.
Jump into concepts and practice - no test required
import numpy as np arr = np.array([3, 1, 2, 3, 2, 4]) unique_arr = np.unique(arr) print(unique_arr)
| Step | Action | Input/State | Result/Output |
|---|---|---|---|
| 1 | Input array created | [3, 1, 2, 3, 2, 4] | [3 1 2 3 2 4] |
| 2 | Sort array internally | [3 1 2 3 2 4] | [1 2 2 3 3 4] |
| 3 | Find unique elements | [1 2 2 3 3 4] | [1 2 3 4] |
| 4 | Return unique array | - | [1 2 3 4] |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| arr | - | [3 1 2 3 2 4] | [3 1 2 3 2 4] | [3 1 2 3 2 4] | [3 1 2 3 2 4] |
| unique_arr | - | - | - | [1 2 3 4] | [1 2 3 4] |
np.unique(array) - Returns sorted unique elements from array - Does not modify original array - Useful to find distinct values - Output is always sorted - Can return indices or counts with options
np.unique() function do when applied to a NumPy array?np.unique() extracts all different values from the input array and sorts them.np.unique() does.arr?np.unique(arr).import numpy as np arr = np.array([3, 1, 2, 3, 2, 1, 4]) result = np.unique(arr) print(result)
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)
arr.unique(), but NumPy arrays do not have a method named unique().np.unique(arr), a function in the NumPy module, not a method of the array object.arr = np.array([[1, 2, 2], [3, 1, 4]]), which code correctly finds all unique elements in the entire array?np.unique(arr) flattens the array and returns all unique elements sorted.axis=0 or axis=1 returns unique rows or columns, not unique elements overall.arr.unique() is invalid because arrays do not have a unique method.