Advanced Universal Functions (ufuncs)

Reference:

import numpy as np

arr = np.array([1, 4, 9, 16, 25])

# Advanced mathematical functions
sqrt_arr = np.sqrt(arr)              # Square root
log_arr = np.log(arr)                # Natural log
log10_arr = np.log10(arr)            # Base-10 log
exp_arr = np.exp([1, 2, 3])          # Exponential
sin_arr = np.sin(np.pi * arr)        # Trigonometric

Advanced Broadcasting

Reference:

# Broadcasting 1D to 2D
row = np.array([1, 2, 3])
col = np.array([[1], [2]])
result = row + col          # Shape (2, 3)

# Broadcasting rules:
# 1. If arrays have different dimensions, prepend 1s to smaller shape
# 2. Arrays are compatible if dimensions are equal or one is 1
# 3. After broadcasting, each array behaves as if it had shape equal to elementwise max

Array Stacking and Concatenation

Reference:

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Stacking
vstacked = np.vstack([arr1, arr2])   # Vertical: shape (2, 3)
hstacked = np.hstack([arr1, arr2])   # Horizontal: shape (6,)
dstacked = np.dstack([arr1, arr2])   # Depth: shape (1, 3, 2)

# Concatenation with axis
arr_2d1 = np.array([[1, 2], [3, 4]])
arr_2d2 = np.array([[5, 6], [7, 8]])
concatenated = np.concatenate([arr_2d1, arr_2d2], axis=0)  # Stack rows

Linear Algebra Operations

Reference:

A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

# Matrix multiplication
C = A @ B                   # or np.dot(A, B)
C_alt = np.matmul(A, B)     # Alternative

# Matrix operations
det = np.linalg.det(A)      # Determinant
inv = np.linalg.inv(A)      # Matrix inverse
rank = np.linalg.matrix_rank(A)  # Matrix rank

# Eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eig(A)

# Solve linear system Ax = b
b = np.array([1, 2])
x = np.linalg.solve(A, b)

Advanced Indexing

Reference:

# Using np.ix_ for outer indexing
arr = np.arange(20).reshape(4, 5)
rows = [0, 2]
cols = [1, 3, 4]
result = arr[np.ix_(rows, cols)]

# Using ellipsis for arbitrary dimensions
arr_3d = np.random.randn(2, 3, 4)
result = arr_3d[..., 0]  # Same as arr_3d[:, :, 0]

Random Number Generation

Reference:

# Modern random number generation (NumPy 1.17+)
from numpy.random import default_rng
rng = default_rng(seed=42)

# Generate random arrays
uniform = rng.uniform(0, 1, size=(3, 3))       # Uniform [0, 1)
normal = rng.normal(0, 1, size=(3, 3))         # Normal distribution
integers = rng.integers(1, 10, size=(3, 3))    # Random integers

# Random sampling
choices = rng.choice([1, 2, 3, 4, 5], size=10, replace=True)
shuffled = rng.permutation([1, 2, 3, 4, 5])

# Legacy interface (still works)
np.random.seed(42)
old_style = np.random.randn(3, 3)

Set Operations

Reference: