Back to Study Material Python

NumPy

NumPy (Numerical Python) is the foundational library for numerical computing in Python. It provides the ndarray object, a fast and memory-efficient multi-d...

NumPy

What is NumPy?

NumPy (Numerical Python) is the foundational library for numerical computing in Python. It provides the ndarray object, a fast and memory-efficient multi-dimensional array, along with hundreds of mathematical functions that operate on those arrays.

Before NumPy, Python lists could store numbers, but performing math on them required slow loops. NumPy arrays store data in contiguous memory blocks and use compiled C code under the hood, making operations 10x to 100x faster than equivalent Python loops.

Installing NumPy is straightforward: pip install numpy. Import it as np by convention: import numpy as np.

Creating arrays: a = np.array([1, 2, 3, 4]) # 1-D array b = np.zeros((3, 4)) # 3x4 matrix of zeros c = np.arange(0, 10, 2) # [0, 2, 4, 6, 8] d = np.linspace(0, 1, 5) # 5 evenly spaced values from 0 to 1

Key attributes of every ndarray: shape (dimensions), dtype (data type), and ndim (number of axes). Knowing these helps you debug shape mismatches, the most common NumPy error.

Broadcasting lets NumPy perform arithmetic between arrays of different shapes without copying data. For example, adding a (3,) vector to a (4, 3) matrix applies the vector to each of the four rows automatically.

Indexing and slicing work like Python lists but extend to multiple dimensions. a[1:3, 0:2] extracts rows 1-2 and columns 0-1 from a 2-D array.

Aggregation functions summarize data in one line: np.sum, np.mean, np.std, np.min, np.max. Passing axis=0 aggregates down rows; axis=1 aggregates across columns.

Practical tip: Always check array shapes with .shape before matrix multiplication. Use np.dot(A, B) or the @ operator for matrix products; the * operator performs element-wise multiplication, not matrix multiplication.

Exam tip: Remember that NumPy array slices return views, not copies. Modifying a slice modifies the original array. Use .copy() when you need an independent array.