</>
Skip to content
Python lessons (42/45)

Python — NumPy

Install & import

pip install numpy
import numpy as np          # the universal alias

Why NumPy exists

Python lists do math with loops:

prices = [10.0, 20.0, 30.0]
doubled = [p * 2 for p in prices]     # slow loop, verbose

NumPy arrays do whole-array math at C speed:

a = np.array([10.0, 20.0, 30.0])

a * 2            # array([20., 40., 60.])  — one expression!
a + 5            # adds to every element
np.sqrt(a)       # element-wise square roots

This "apply the operation everywhere" behavior is called vectorization — NumPy's entire reason for being.

Creating arrays

np.array([1, 2, 3])                    # from a list
np.zeros((3, 4))                       # 3×4 of 0.0
np.ones(5)
np.arange(0, 10, 2)                    # like range: 0,2,4,6,8
np.linspace(0, 1, 5)                   # 5 evenly spaced: [0, .25, .5, .75, 1]
np.random.randint(1, 7, size=(3, 3))   # random matrix (dice rolls)

Shape & dimensions

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

m.shape        # (2, 3) — rows, columns
m.ndim         # 2
m.size         # 6
m.dtype        # int64 — one type per array

Indexing & slicing

m[1, 2]        # row 1, col 2 → 6
m[0]           # first row
m[:, 0]        # ALL rows, column 0 → [1, 4]
m[m > 2]       # boolean mask → [3, 4, 5, 6]  ← filtering by condition!

That last line — filtering an array by a comparison — is NumPy's signature move.

Aggregations

a = np.array([21.5, 22.1, 19.8])

a.mean(); a.sum(); a.min(); a.max()
a.std()                  # standard deviation
m.sum(axis=0)            # per-column sums
m.sum(axis=1)            # per-row sums

Real example — grade analysis

scores = np.array([88, 92, 79, 95, 67])

scores.mean()                     # class average
scores - scores.mean()            # each student vs average
np.where(scores >= 90, "A", "B")  # conditional per element
len(scores[scores < 80])          # count below 80 → 2

Broadcasting preview

Arrays of different shapes still combine when compatible:

m = np.array([[1, 2], [3, 4]])
row = np.array([10, 20])

m + row        # [[11,22],[13,24]] — row added to EVERY row

Gotchas: one wrong-typed value upcasts everything to float · a[1:] slices are VIEWS (mutating them changes a!) · == on arrays returns an array of booleans, not one bool.

Mini Practice

  1. Vectorize a list-comprehension you wrote earlier; time both.
  2. Dice-roll matrix 1000×6; compute per-column means.
  3. Boolean-mask filter temperatures above average.
  4. np.where grades: ≥90 A, ≥80 B, else C.
  5. Prove the view-mutation gotcha; fix with .copy().

Next: pandas →

Related Topics

Frequently Asked Questions about NumPy

What is NumPy in Python?

NumPy is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn NumPy?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn NumPy.

Why is NumPy important in Python?

NumPy is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.