0
0
NumPydata~10 mins

np.unique() for unique values in NumPy - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
NumPy
import numpy as np
arr = np.array([3, 1, 2, 3, 2, 4])
unique_vals = np.unique(arr)
print(unique_vals)
This code finds and prints the unique values from the given array.
Execution Table
StepActionArray StateResult
1Input array created[3, 1, 2, 3, 2, 4]Original array
2Sort array internally[1, 2, 2, 3, 3, 4]Sorted array for processing
3Identify unique values[1, 2, 3, 4]Unique values extracted
4Return unique array[1, 2, 3, 4]Output array with unique values
💡 All unique values identified and returned as a sorted array.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
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_valsN/AN/A[1, 2, 3, 4][1, 2, 3, 4]
Key Moments - 2 Insights
Why does np.unique() return a sorted array of unique values?
np.unique() sorts the array internally to easily identify unique values in order, as shown in step 2 and 3 of the execution_table.
Does np.unique() change the original array?
No, the original array 'arr' remains unchanged throughout, as shown in variable_tracker where 'arr' keeps its initial values.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the array state?
A[3, 1, 2, 3, 2, 4]
B[1, 2, 2, 3, 3, 4]
C[1, 2, 3, 4]
D[4, 3, 2, 1]
💡 Hint
Check the 'Array State' column at step 3 in the execution_table.
At which step does np.unique() identify unique values?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column in the execution_table to find when unique values are identified.
If the input array was already sorted, how would step 2 change?
AStep 2 would still sort but no change in array
BStep 2 would be skipped
CStep 2 would reverse the array
DStep 2 would remove duplicates
💡 Hint
np.unique() always sorts internally even if the array is sorted; see step 2 in execution_table.
Concept Snapshot
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
Full Transcript
np.unique() is a function in numpy that finds all unique values in an array. It first sorts the array internally, then identifies unique values by removing duplicates. The original array stays the same. The function returns a new array with unique values sorted in ascending order. This is useful when you want to know which distinct values exist in your data. The execution steps show the input array, sorting, unique identification, and final output. Variables track the original and unique arrays separately to avoid confusion.