Essential NumPy Functions
Reference guide for np.unique, np.argsort, np.random.randint, and np.eye
1. np.unique() - Find Unique Elements
Purpose: Returns the sorted unique elements of an array.
Syntax
numpy.unique(ar, return_index=False, return_inverse=False,
return_counts=False, axis=None)
Parameters
| Parameter | Description |
|---|---|
| ar | Input array |
| return_index | If True, return indices of first occurrences |
| return_inverse | If True, return indices to reconstruct original array |
| return_counts | If True, return count of each unique element |
| axis | Axis along which to find unique values |
Examples
import numpy as np
# Basic usage
arr = np.array([1, 2, 2, 3, 3, 3, 4])
unique_vals = np.unique(arr)
print(unique_vals) # [1 2 3 4]
# With counts
values, counts = np.unique(arr, return_counts=True)
print(values) # [1 2 3 4]
print(counts) # [1 2 3 1]
# With indices
arr = np.array([3, 1, 2, 1, 3])
values, indices = np.unique(arr, return_index=True)
print(values) # [1 2 3]
print(indices) # [1 2 0] - first occurrence positions
# With inverse (reconstruct original)
values, inverse = np.unique(arr, return_inverse=True)
print(values) # [1 2 3]
print(inverse) # [2 0 1 0 2]
print(values[inverse]) # Reconstructs original: [3 1 2 1 3]
# 2D array along axis
arr_2d = np.array([[1, 2], [3, 4], [1, 2]])
unique_rows = np.unique(arr_2d, axis=0)
print(unique_rows)
# [[1 2]
# [3 4]]2. np.argsort() - Indices for Sorting
Purpose: Returns the indices that would sort an array.
Syntax
numpy.argsort(a, axis=-1, kind=None, order=None)
Parameters
| Parameter | Description |
|---|---|
| a | Array to sort |
| axis | Axis along which to sort (-1 for last axis) |
| kind | Sorting algorithm: 'quicksort', 'mergesort', 'heapsort', 'stable' |
| order | Field names for structured arrays |
Examples
import numpy as np
# Basic usage
arr = np.array([3, 1, 4, 1, 5])
indices = np.argsort(arr)
print(indices) # [1 3 0 2 4]
print(arr[indices]) # [1 1 3 4 5] - sorted array
# Descending order (reverse)
indices_desc = np.argsort(arr)[::-1]
print(arr[indices_desc]) # [5 4 3 1 1]
# Or using negative values
indices_desc = np.argsort(-arr)
print(arr[indices_desc]) # [5 4 3 1 1]
# 2D array - sort along axis
arr_2d = np.array([[3, 1, 4],
[1, 5, 9]])
# Sort each row
indices = np.argsort(arr_2d, axis=1)
print(indices)
# [[1 0 2]
# [0 1 2]]
# Sort each column
indices = np.argsort(arr_2d, axis=0)
print(indices)
# [[1 0 0]
# [0 1 1]]
# Practical: Sort by multiple columns
data = np.array([[2, 3],
[1, 2],
[2, 1]])
# Sort by first column, then second
idx = np.lexsort((data[:, 1], data[:, 0]))
print(data[idx])
# [[1 2]
# [2 1]
# [2 3]]3. np.random.randint() - Random Integers
Purpose: Generate random integers from a specified range.
Syntax
numpy.random.randint(low, high=None, size=None, dtype=int)
Parameters
| Parameter | Description |
|---|---|
| low | Lowest integer (inclusive), or highest if high=None |
| high | Highest integer (exclusive) |
| size | Output shape (int or tuple) |
| dtype | Data type of output |
Examples
import numpy as np
# Single random integer [0, 10)
num = np.random.randint(10)
print(num) # e.g., 7
# Random integer in range [5, 15)
num = np.random.randint(5, 15)
print(num) # e.g., 12
# Array of random integers
arr = np.random.randint(0, 10, size=5)
print(arr) # e.g., [3 7 2 9 1]
# 2D array of random integers
arr_2d = np.random.randint(0, 100, size=(3, 4))
print(arr_2d)
# e.g., [[45 23 67 89]
# [12 56 34 78]
# [90 11 44 55]]
# Random dice rolls
dice_rolls = np.random.randint(1, 7, size=10)
print(dice_rolls) # e.g., [3 6 2 4 1 5 6 3 2 4]
# Set seed for reproducibility
np.random.seed(42)
arr1 = np.random.randint(0, 10, size=5)
np.random.seed(42)
arr2 = np.random.randint(0, 10, size=5)
print(arr1 == arr2) # All True
# Modern way (recommended): using Generator
rng = np.random.default_rng(seed=42)
arr = rng.integers(0, 10, size=5)
print(arr)4. np.eye() - Identity Matrix
Purpose: Create a 2D array with ones on the diagonal and zeros elsewhere
(identity matrix).
Syntax
numpy.eye(N, M=None, k=0, dtype=float, order='C')
Parameters
| Parameter | Description |
|---|---|
| N | Number of rows |
| M | Number of columns (defaults to N) |
| k | Index of diagonal (0=main, positive=upper, negative=lower) |
| dtype | Data type of output |
| order | Row-major ('C') or column-major ('F') |
Examples
import numpy as np
# 3x3 identity matrix
I = np.eye(3)
print(I)
# [[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]
# 4x4 identity matrix with integers
I = np.eye(4, dtype=int)
print(I)
# [[1 0 0 0]
# [0 1 0 0]
# [0 0 1 0]
# [0 0 0 1]]
# Non-square matrix (3 rows, 5 columns)
I = np.eye(3, 5)
print(I)
# [[1. 0. 0. 0. 0.]
# [0. 1. 0. 0. 0.]
# [0. 0. 1. 0. 0.]]
# Diagonal offset (k=1, upper diagonal)
I = np.eye(4, k=1)
print(I)
# [[0. 1. 0. 0.]
# [0. 0. 1. 0.]
# [0. 0. 0. 1.]
# [0. 0. 0. 0.]]
# Diagonal offset (k=-1, lower diagonal)
I = np.eye(4, k=-1)
print(I)
# [[0. 0. 0. 0.]
# [1. 0. 0. 0.]
# [0. 1. 0. 0.]
# [0. 0. 1. 0.]]
# Practical: Matrix multiplication with identity
A = np.array([[1, 2], [3, 4]])
I = np.eye(2)
result = A @ I # Same as A
print(np.array_equal(A, result)) # TruePractical Use Cases
Use Case 1: Data Cleaning with np.unique()
import numpy as np
# Remove duplicates from dataset
data = np.array([1, 2, 2, 3, 3, 3, 4, 5, 5])
clean_data = np.unique(data)
# Find most common value
values, counts = np.unique(data, return_counts=True)
most_common = values[np.argmax(counts)]
print(f"Most common: {most_common}") # 3
Use Case 2: Top-K Elements with np.argsort()
import numpy as np
scores = np.array([85, 92, 78, 95, 88, 76, 90])
names = np.array(['Alice', 'Bob', 'Charlie', 'David',
'Eve', 'Frank', 'Grace'])
# Get top 3 students
top_3_indices = np.argsort(scores)[-3:][::-1]
print("Top 3:")
for i in top_3_indices:
print(f"{names[i]}: {scores[i]}")Use Case 3: Simulation with np.random.randint()
import numpy as np
# Simulate 1000 coin flips (0=tails, 1=heads)
flips = np.random.randint(0, 2, size=1000)
heads_count = np.sum(flips)
print(f"Heads: {heads_count}, Tails: {1000 - heads_count}")
# Simulate rolling two dice 100 times
dice1 = np.random.randint(1, 7, size=100)
dice2 = np.random.randint(1, 7, size=100)
totals = dice1 + dice2
print(f"Average roll: {np.mean(totals):.2f}")Use Case 4: Linear Algebra with np.eye()
import numpy as np
# Create augmented matrix for solving Ax = b
A = np.array([[2, 1], [1, 3]])
I = np.eye(2)
# Check if matrix is invertible
det = np.linalg.det(A)
if det != 0:
A_inv = np.linalg.inv(A)
# Verify: A * A_inv = I
result = A @ A_inv
print(np.allclose(result, I)) # TrueQuick Reference Comparison
| Function | Primary Use | Returns |
|---|---|---|
| np.unique() | Find unique elements | Sorted unique values |
| np.argsort() | Get sorting indices | Array of indices |
| np.random.randint() | Generate random integers | Random integer(s) |
| np.eye() | Create identity matrix | 2D array with diagonal ones |
Key Takeaways
Remember:
- np.unique() - Remove duplicates, count occurrences
- np.argsort() - Get indices for sorting (use negative for descending)
- np.random.randint() - Generate random integers (high is exclusive)
- np.eye() - Create identity matrices for linear algebra
- All functions support multi-dimensional arrays
- Use
return_counts=Truewith unique() for frequency analysis - Use
np.random.default_rng()for modern random number generation