Skip to main content

Command Palette

Search for a command to run...

NumPy Demystified

Published
5 min readView as Markdown

NumPy (Numerical Python) is an open-source Python library that provides support for large, mulit-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. It is the backbone of the scientific Python ecosystem, enabling efficient numerical computations and serving as a base for libraries like SciPy, Pandas, and scikit-learn.

Arithmetic Functions


These operate element-wise on arrays.

np.add(x1,x2)

Add elements of two arrays.

np.add([1,2],[3,4]) # → array([4,6])`

Use case: Vectorized addition of columns in a dataset.

np.subtract(x1,x2)

Subtracts elements of the second array from the first.

np.subtract([10,20],[1,2]) # → array([9,18])`

Use case: Difference between predictions and actual values.

np.multiply(x1,x2)

Element-wise multiplication.

np.multiply([1,2][3,4]) # → array([3,8])

Use case: Scaling arrays or computing dot components.

np.divide(x1,x2)

Element-wise division.

np.divide([10,20],[2,4]) # → array([5.,5.])

Use case: Normalize values.

Statistical Functions


np.mean(a, axis=None)

Returns the average of elements.

np.mean([1,2,3,4]) # → 2.5

Use case: Central tendency of feature columns.

np.median(a, axis =None)

Returns the median(middle value).

np.median([1,3,5,100]) # → 4.0

Use case: Analyze skewed data.

np.std(a)

Standard deviation of the array.

np.std([1,2,3]) # → 0.8165

Use case: Measure the spread of features or errors.

np.var(a)

Returns the variance.

np.var([1,2,3]) # → 0.666…

Use case: Feature engineering and normalization.

Cumulative Functions


np.cumsum(a)

Cumulative sum of elements.

np.cumsum([1,2,3]) # → array([1,3,6])

Use case: Time-series trend tracking.

np.cumprod(a)

Cumulative product of elements.

np.cumprod([1,2,3]) #array([1,2,6])

Use case: Compound growth rates in finance.

Trigonometric & Exponential


np.sin(x), np.cos(x), np.tan(x)

Compute the trigonometric values element-wise.

np.sin(np.pi/2) # → 1.0

Use case: Signal analysis, physics simulations.

np.exp(x)

Computes e^x for each element.

np.exp([0,1]) # → array([1. , 2.71828183])

Use case: Exponential growth models.

np.log(x), np.log10(x)

Natural and base-10 logarithms.

np.log([1, np.e])               # → [0.0 , 1.0 ]
np.log10([1, 10, 100])       # → [0. , 1. , 2. ]

Use case: Log transforms in data preprocessing.

Reshaping and Transposing


np.reshape(a, new_shape)

Changes the shape without changing the data.

a = np.arrange(6)       # → [0 1 2 3 4 5]
a.reshape(2,3)          # → [[0 1 2],[3 4 5]]

Use case: Feeding data into models expecting certain dimensions.

np.transpose(a)

Swaps rows and columns (for 2D).

a = np.array([[1,2],[3,4]])
np.transpose(a)   # → [[1,3],[2,4]]

Use case: Matrix algebra, image manipulations.

Stacking & Splitting


np.vstack(tup)

Stacks arrays vertically (row-wise).

a = np.array([1,2])
b = np.array([3,4])

np.vstack((a,b))     # → [[1,2][3,4]]

Use case: Concatenate batches of data vertically.

np.hstack(tup)

Stacks arrays horizontally (column-wise).

np hstack((a,b))   # → [1,2,3,4]

Use case: Combine features into a single array.

np.split(a, indices_or_sections)

Splits an array into multiple sub-arrays.

a = np.array([1,2,3,4])
np.split(a,2)     # → [array([1,2]), array([3,4])]

Use case: Data partitioning for training and testing.

Logical & Comparison Functions


np.where(condition, x, y)

Returns elements from x or y based on the condition.

np.where([True, False], [1,2], [3,4])   # → [1,4]

Use case: Conditional transformations in arrays.

Element-wise conditional selection.

arr = np.array([1,2,3,4])
np.where(arr%2 == 0, “even”, “odd”)   
# → [‘odd’, ‘even’, ‘odd’, ‘even’]

Use case: Label encoding, masking, and quick logic branching.

np.all() / np.any()

Check if all / any elements are True.

np.all([True, True]) # → True
np.any([Flase, True]) # → True

Use case: Validate masks or filter conditions.

Matrix Operations


These are core when working with 2D arrays, especially in ML, computer vision, and physics.

np.dot(a,b)

Performs matrix multiplication or dot product of 1D arrays.

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

np.dot(a,b) # → array([[19, 22],[43, 50]])

Use case: Feedforward pass in neural networks.

np.matmul(a,b) or a @ b

Same as np.dot, but with better handling for 3D arrays or tensors.

Use case: Deep learning matrix chaining or RRNs with 3D tensors.

np.outer(a,b)

Computes the outer product of two 1D arrays.

np.outer([1,2],[3,4])  # → array([[3,4],[6,8]])

Use case: Construct Gram matrices or pairwise similarity.

np.cross(a,b)

Cross product (for 3D vectors).

np.cross([1,0,0], [0,1,0])     # → array([0, 0, 1])

Use case: Physics, 3D geometry, robotics.

Linear Algebra Functions (np.linalg)


NumPy has a powerful linear algebra module (numpy.linalg).

np.linalg.inv(a)

Inverse of a matrix.

a = np.array([[1, 2], [3, 4]])
np.linalg.inv(a)

Use case: Solving systems of equations, backpropagation.

np.linalg.det(a)

Determinant of a square matrix.

np.linalg.det([[1,2], [3,4]])   # → -2.0

Use case: Matrix invertibility checks or volume in geometry.

np.linalg.eig(a)

Eigenvalues and eigenvectors.

vals = vecs = np.linalg.eig([[2, 0], [0, 3]])

Use case: PCA, spectral clustering, dynamical systems.

np.linalg.svd(a)

Singular Value Decomposition

U, S, Vt = np.linalg.svd([[1, 2], [3, 4]])

Use case: Dimensionality reduction, image compression.

np.linalg.solve(A, B)

Solve Ax = B for x.

A = np.array([[3, 1], [1, 2]])
B = np.array([9, 8])

np.linalg.solve(A, B)      # → [2, 3]

Use case: Linear system solvers ( regression, physics models).

Random Number Generation (np.random)


Useful for simulating data, initializing weights, or bootstrapping.

np.random.rand(d0, d1, …)

Uniform distribution over [0,1).

np.random.rand(2, 2)

Use case: Weight initialization in neural nets.

np.random.randn(d0, d1, …)

Standard normal distribution (mean 0, std 1).

np.random.randn(3)    # e.g., array([0.23, -1.4, 0.88])

Use case: Simulating Gaussian noise.

np.random.randint(low, high, size)

Random integers between low and high.

np.random.randint(0, 10, size=(2, 2))

Use case: Label generation or sampling indices.

np.random.choice(a, size, replace, p)

Randomly picks elements with or without replacement.

np.random.choice([1, 2, 3], size = 2, replace = False)

Use case: Shuffle or bootstrap samples from a dataset.

np.random.seed(seed)

Sets the seed for reproducibility.

np.random.seed(42)

Use case: Ensure reproducible experiments in research or ML training.

Miscellaneous


np.clip(a, min, max)

Clips values outside the range.

np.clip([1 , 5, 10], 0, 5)    # → [1, 5, 5]

Use case: Clamp predictions, outlier removal, normalization boundaries.

np.unique()

Finds the unique values and optionally their counts.

np.unique([1, 2, 1, 3, 2], reurn_counts = True)     
# → (array([1, 2, 3]), array([2, 2, 1]))

Use case: Deduplication, class distribution in classification.

np.isnan(), np.isinf(), np.isfinite()

Detect NaNs and infinities.

arr = np.array([1, np.nan, np.inf])
np.isnan(arr)  # → [False, True, False]

Use case: Cleaning or validating datasets before ML training.