0
0
NumPydata~10 mins

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

Choose your learning style9 modes available
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.
Execution Sample
NumPy
import numpy as np
arr = np.array([3, 1, 2, 3, 2, 4])
unique_arr = np.unique(arr)
print(unique_arr)
This code finds unique elements from the array and prints them sorted.
Execution Table
StepActionInput/StateResult/Output
1Input array created[3, 1, 2, 3, 2, 4][3 1 2 3 2 4]
2Sort array internally[3 1 2 3 2 4][1 2 2 3 3 4]
3Find unique elements[1 2 2 3 3 4][1 2 3 4]
4Return unique array-[1 2 3 4]
💡 All unique elements extracted and returned as sorted array.
Variable Tracker
VariableStartAfter Step 1After 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]
unique_arr---[1 2 3 4][1 2 3 4]
Key Moments - 2 Insights
Why does np.unique() return a sorted array instead of preserving the original order?
np.unique() sorts the array internally to efficiently find unique elements, so the output is always sorted as shown in step 2 and 3 of the execution_table.
Does np.unique() change the original array?
No, np.unique() does not modify the original array 'arr'. It returns a new array with unique elements, as seen in variable_tracker where 'arr' stays the same.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output after step 3?
A[3 1 2 3 2 4]
B[1 2 3 4]
C[1 2 2 3 3 4]
D[4 3 2 1]
💡 Hint
Check the 'Result/Output' column for step 3 in the execution_table.
At which step does np.unique() sort the array internally?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column in the execution_table for sorting.
If the input array was already sorted, how would the execution_table change?
AStep 2 would show the same sorted array as input
BStep 3 would return duplicates
CStep 4 would return the original array
DStep 1 would be skipped
💡 Hint
Refer to the sorting step and its output in the execution_table.
Concept Snapshot
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
Full Transcript
np.unique() is a function in numpy that finds unique elements in an array. It first sorts the array internally, then extracts unique values, and returns them as a new sorted array. The original array remains unchanged. This process helps to quickly identify distinct values in data. The output is always sorted, which is important to remember when order matters.