Concept Flow - np.unique() for unique values
Input Array
Sort Array
Identify Unique Values
Return Unique Values Array
np.unique() takes an array, sorts it, finds unique values, 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_vals = np.unique(arr) print(unique_vals)
| Step | Action | Array State | Result |
|---|---|---|---|
| 1 | Input array created | [3, 1, 2, 3, 2, 4] | Original array |
| 2 | Sort array internally | [1, 2, 2, 3, 3, 4] | Sorted array for processing |
| 3 | Identify unique values | [1, 2, 3, 4] | Unique values extracted |
| 4 | Return unique array | [1, 2, 3, 4] | Output array with unique values |
| Variable | Start | 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] (unchanged) |
| unique_vals | N/A | N/A | [1, 2, 3, 4] | [1, 2, 3, 4] |
np.unique(array) - Returns sorted unique values from array - Does not change original array - Useful to find distinct elements - Output is always sorted - Can return indices or counts with options
np.unique() function do in NumPy?np.unique()np.unique() does.np.unique() = unique values [OK]arr?unique is part of the NumPy module and is called as np.unique().arr.unique() is not a NumPy array method, unique(arr) misses the module prefix, and np.arr.unique() is invalid syntax.import numpy as np arr = np.array([3, 1, 2, 3, 2, 1, 4]) print(np.unique(arr))
np.unique() output ordernp.unique() returns sorted unique values, so output is [1 2 3 4].import numpy as np arr = [1, 2, 2, 3] print(np.unique(arr, return_counts=True))
np.unique() accepts lists or arrays as input without error.return_counts argumentreturn_counts=True is valid and returns counts of unique values.arr = np.array([[1, 2, 2], [3, 1, 4]])
np.unique() on 2D arraysnp.unique() without axis flattens the array and returns unique sorted values.axis=0 or axis=1 returns unique rows or columns, not unique elements overall.