Skip to main content
NumPy (Numerical Python) is the foundational library for numerical computing in Python. At its core is the ndarray — an N-dimensional array object stored in contiguous memory where every element shares the same data type. Because NumPy operations are executed by pre-compiled C code rather than the Python interpreter, array-wide calculations run orders of magnitude faster than equivalent Python loops. Every major data science library — Pandas, Matplotlib, SciPy, Scikit-learn, TensorFlow, PyTorch — builds directly on NumPy, making it an essential skill before you touch any of them.

Installation and Import

The alias np is a universal convention. You’ll see it in every tutorial, Stack Overflow answer, and official example — use it from the start so your code looks familiar to other developers.

Why NumPy Arrays?

Standard Python lists can hold mixed types and require Python-level loops for math. NumPy arrays are homogeneous (one data type throughout) and operations are vectorized — executed in bulk by compiled C code.

Creating Arrays

From Python lists

Zeros, Ones, and Empty

Always pass multi-dimensional shapes as a tuple to np.zeros, np.ones, and np.empty. Writing np.zeros(2, 3) raises a TypeError because NumPy interprets the second argument as a dtype parameter.

Ranges

Linearly Spaced Values

Random Numbers

Array Properties

Indexing and Slicing

1D Arrays

2D Arrays

For 2D arrays, use arr[row_slice, column_slice]:

Boolean (Conditional) Filtering

Use bitwise operators & (AND) and | (OR) — not Python’s and/or — when combining NumPy boolean conditions. Also wrap each condition in its own parentheses to ensure correct operator precedence.

Array Manipulation

Reshaping

The total number of elements must remain the same after reshaping, otherwise NumPy raises a ValueError.

Flattening

Transposing

Combining and Splitting Arrays

Sorting and Copying

Views vs. copies:

Aggregate Functions

Vector Operations (Vectorization)

Vectorization means applying an operation to an entire array in a single statement, with no explicit Python loop. NumPy dispatches the calculation to compiled C code, making it dramatically faster.
Common vector operations:
Real-world example — salary increment:

Broadcasting

Broadcasting lets you perform arithmetic between arrays of different shapes without manually copying data. NumPy logically expands the smaller array to match the larger one. Broadcasting rules (compared right to left):
  • Dimensions are compatible if they are equal, or if one of them is 1.
  • If incompatible, NumPy raises a ValueError.
Broadcasting failure:
Easy rule to remember: Broadcasting prepares the array shapes → Vectorization performs the element-wise computation. They work as a pair: broadcasting first, computation second.