Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 38 ยท Getting Started

NumPy Refresher for SciPy

Review the NumPy skills SciPy relies on: array shape and dtype, slicing, broadcasting, vectorization, linspace, seeded random numbers and basic plots.

Every SciPy function takes NumPy arrays in and hands NumPy arrays out, so a few NumPy habits decide whether your SciPy code is short and fast or long and confusing. This lesson is a focused refresher, not a full NumPy course. If any part feels new, the NumPy lesson in the Python tutorial goes deeper.

We cover the six things you will use in nearly every later lesson: shape and dtype, slicing, broadcasting, vectorization, evenly spaced grids and reproducible random numbers. Then we finish with the plotting pattern used throughout this tutorial.

Shape and dtype

An ndarray is a grid of values that all share one dtype (such as int64 or float64) and have a shape: a tuple with the length along each axis. Numerical code cares about both. A shape mismatch is the most common error you will see, and a wrong dtype (integers where you need floats) can silently change results.

Python Shape, dtype and views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the last two lines. Slices are views, not copies: they share memory with the original, so writing to view changed grid. Use .copy() when you need an independent array. Boolean masks and lists of indices, by contrast, return copies.

Most SciPy routines convert their input to float64 for you, but building your arrays as floats (1.0 instead of 1, or dtype=float) avoids surprises such as integer overflow or integer division in your own code.

Broadcasting

Broadcasting lets arrays of different shapes combine in one operation. NumPy compares the shapes from the right-hand end: two dimensions are compatible when they are equal or when one of them is 1, and a size-1 dimension is stretched to match.

flowchart LR
    A["col<br/>shape (2, 1)"] --> R["result<br/>shape (2, 3)"]
    B["row<br/>shape (3,)"] --> R

A column of shape (2, 1) and a row of shape (3,) stretch against each other into a (2, 3) result.

Python Broadcasting a column and a row

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Broadcasting is how you subtract a mean from every row, scale columns, or build a multiplication table without writing a loop. When shapes are incompatible NumPy raises ValueError: operands could not be broadcast together, and printing .shape of both operands finds the problem quickly.

Vectorization

A vectorized operation applies to a whole array at once, with the loop running in compiled code. Compare a Python loop with the array expression:

Python Loop versus vectorized sum of squares

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both give the same answer, but with a million elements the vectorized version is typically 50 to 100 times faster. The rule for this tutorial: if you catch yourself writing for i in range(len(x)) over a numeric array, look for an array expression, a NumPy function such as np.cumsum, or a SciPy function that does the whole job.

Tip: Functions such as np.sin, np.exp and np.sqrt (called universal functions) work element-wise on arrays. The math module versions only accept single numbers.

Grids and seeded random numbers

Numerical work constantly needs an evenly spaced set of x values and some test data.

  • np.linspace(start, stop, num) returns num points including the end point. Use it when you know how many points you want.
  • np.arange(start, stop, step) excludes the stop value and can produce surprising lengths with float steps. Prefer linspace for floats.
  • np.random.default_rng(seed) creates a random generator. The same seed always gives the same numbers, which makes examples and tests repeatable.
Python linspace and default_rng

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The two generators created with seed 42 produce the same first five integers. Always use a generator object (rng.normal(...)) rather than the old global np.random.seed, because it is cleaner and safe to pass around. Every example here that uses randomness fixes the seed, so you see the same output as the text.

A figure in four steps

SciPy results are easier to trust when you plot them. The pattern used in this tutorial is:

  1. Compute arrays with NumPy and SciPy.
  2. Create a figure and axes with fig, ax = plt.subplots().
  3. Draw with ax.plot, ax.scatter or ax.imshow, and add labels.
  4. Call plt.show().
Python Two plots in one figure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The left plot draws two curves from 200 linspace points; the right one scatters 60 random points. The Matplotlib lesson covers styles and more chart types.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the shape of the result of adding an array of shape (2, 1) to an array of shape (3,)?

    Shapes are compared from the right. 1 stretches to 3, and the missing leading dimension of the second array is treated as 1, which stretches to 2. The result has shape (2, 3).
  2. 2. What happens to a NumPy array when you change a slice of it, such as b = a[0]; b[0] = 99?

    Basic slices share memory with the original array. Use .copy() if you need an independent array.
  3. 3. Why should examples use np.random.default_rng(42)?

    A seeded generator makes experiments and tests reproducible. Anyone running the same code gets the same numbers.
  4. 4. Which is usually the best way to compute the square of every element of a large array x?

    The vectorized expression runs the loop in compiled code and is much faster than looping in Python.

Summary

  • Every array has a shape and one dtype; build numeric arrays as floats when in doubt.
  • Basic slices are views; use .copy() for an independent array.
  • Broadcasting compares shapes from the right and stretches size-1 dimensions.
  • Prefer vectorized expressions to Python loops.
  • linspace gives a fixed number of points including the end; default_rng(seed) gives repeatable randomness.
  • Plot with fig, ax = plt.subplots() and plt.show().

Next: Constants, Units and Conventions.