Skip to content
Tutorials Center
My learning

Topics

Lesson 109 of 149 ยท Data and the Web

NumPy Basics

Learn NumPy from scratch. Create arrays, read shapes and dtypes, do vectorized math, slice and filter with masks, use broadcasting and compute aggregates.

Python lists are wonderfully flexible, but they're slow for number crunching. Every item is a full Python object, and every + in a loop goes through the interpreter one step at a time. NumPy fixes that with one data type, the array: a block of numbers that all share the same type, stored side by side in memory, with math that runs in fast compiled code. Almost every data tool in Python, from pandas to machine-learning libraries, is built on top of it.

In this lesson you'll create arrays, read their shape and type, do math on whole arrays at once, select data with slices and masks, and let broadcasting combine arrays of different shapes. If you met the standard library's array module, think of NumPy as its far more powerful big sibling.

Note: NumPy is a third-party package. On your own computer you install it with pip install numpy (see Packages and pip). The editors on this page load it automatically when they see import numpy, but the first Run downloads several megabytes, so give it a few extra seconds. Later runs reuse the download.

Creating arrays

The usual import is import numpy as np. Everyone uses the np alias, so you'll see it in every tutorial, answer and codebase. The simplest way to make an array is to pass a list to np.array():

Python Your first arrays

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.

A few things to notice:

  • Arrays print without commas, which is how you can tell them apart from lists at a glance.
  • arange() works like range() but accepts floats and returns an array. When you need an exact number of points between two values, linspace() is the safer choice, because float steps can add up to rounding surprises.
  • For random numbers, create a generator with np.random.default_rng(). Passing a seed makes the "random" values repeat on every run, which is great for testing and for lessons like this one.

Every array has one dtype

Unlike a list, an array holds a single type of value, its dtype. NumPy picks one that fits everything you pass in. Mix integers and floats, and you get floats. Ask for a different type with dtype= when creating, or convert later with astype(), which returns a new array:

Python dtypes and astype()

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 exact integer dtype name (such as int64) can vary between platforms, but the idea doesn't: one array, one type. That's exactly what lets NumPy store values compactly and process them at full speed.

Shape: arrays with more than one dimension

Arrays can have any number of dimensions. A table of numbers is a 2-D array with rows and columns. Three attributes describe the layout:

  • ndim is the number of dimensions.
  • shape is a tuple with the length along each dimension, such as (3, 4) for 3 rows and 4 columns.
  • size is the total number of elements.

reshape() rearranges the same values into a new shape, as long as the total size stays the same. Pass -1 for one dimension and NumPy works it out for you:

Python Shapes and reshape()

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.

Vectorized math

Here's where NumPy shines. Arithmetic on arrays happens element by element, without a loop in your code. NumPy calls this vectorization:

Python Math on whole arrays

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 same code with lists would need a loop or a comprehension for every line. And with lists, * means something completely different: [1, 2] * 3 repeats the list instead of multiplying the numbers.

Functions like np.sqrt, np.abs, np.exp and np.log are called universal functions (ufuncs). They apply to every element and return a new array of the same shape.

How much faster is it?

Speed is the main reason NumPy exists. The difference grows with the size of the data. Let's square a million numbers both ways:

Python Loop versus vectorized

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.

Exact numbers depend on your machine (and run inside the browser here), but NumPy usually wins by a wide margin. The performance lesson shows more ways to measure code like this.

Indexing and slicing

Indexing a 1-D array works just like a list, including negative indexes and slices. For a 2-D array, put the row and column in one pair of brackets, separated by a comma: grid[row, col]. A slice in either position selects a range, and : alone means "all of them":

Python Selecting rows, columns and cells

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.

Slices are views, not copies. Slicing a list makes a new list, but slicing an array gives you a view of the same memory. Changing the view changes the original array. Call .copy() when you want an independent array: top = scores[:2].copy().

Python Views share memory

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.

Boolean masks and fancy indexing

A comparison like scores > 80 gives an array of True/False values, called a mask. Put a mask inside the brackets and you get only the elements where it's True. This is how you filter data in NumPy:

Python Filtering with masks

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.

Two rules trip up almost everyone at first:

  • Combine masks with & (and), | (or) and ~ (not), not with the words and, or and not. Python's keywords expect a single True or False, and NumPy raises a ValueError about an ambiguous truth value.
  • Wrap each comparison in parentheses. & binds more tightly than >, so temps > 20 & temps < 30 doesn't mean what it looks like.

np.where(condition, a, b) picks from a where the condition is True and from b elsewhere, like a vectorized conditional expression.

Broadcasting

What happens when you combine arrays of different shapes? You already saw the simplest case: celsius * 9 multiplies every element by one number. NumPy "stretches" the single value to match the array without actually copying it. This is called broadcasting, and it works for arrays too.

The rule: NumPy compares shapes from the right. Two dimensions are compatible when they're equal or when one of them is 1. A dimension of 1 is stretched to match the other.

Python Broadcasting rows and columns

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.

Multiplying by unit_price, shape (4,), works because its length matches the number of columns. store_bonus has 3 values, one per row, so it must become a column first. Indexing with np.newaxis (or .reshape(-1, 1)) adds a dimension of size 1, turning shape (3,) into (3, 1). Without that step, NumPy can't match 3 against 4 and raises an error.

Aggregates: sum, mean and friends

Aggregate methods boil an array down to a summary: sum(), mean(), min(), max(), std() (standard deviation) and median (as the function np.median()). On a 2-D array, the axis argument decides the direction:

  • No axis: one result for the whole array.
  • axis=0: collapse the rows, giving one result per column.
  • axis=1: collapse the columns, giving one result per row.
Python Aggregates along an axis

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.

argmax() and argmin() return the position of the largest or smallest value rather than the value itself, which is handy for looking up a name in a parallel list. cumsum() gives running totals.

Tip: printing a single NumPy number gives you something like 84.0, but inside a list or tuple it shows up as np.float64(84.0). Convert with float() or .item() before putting results into regular Python structures or JSON.

Common NumPy tools at a glance

Task Code
Array from a list np.array([1, 2, 3])
Ranges np.arange(start, stop, step), np.linspace(start, stop, count)
Filled arrays np.zeros(shape), np.ones(shape), np.full(shape, value)
Random numbers rng = np.random.default_rng(seed) then rng.integers(), rng.random()
Layout a.shape, a.ndim, a.size, a.reshape(r, c), a.T
Filtering a[a > 0], np.where(cond, x, y)
Summaries a.sum(), a.mean(axis=0), a.max(), a.argmax(), np.median(a)
Sorting np.sort(a) (a copy) or a.sort() (in place)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does np.array([1, 2, 3]) * 2 produce?

    Arithmetic on arrays is element-wise, so every value is doubled. Repetition is what * does for lists.
  2. 2. m has shape (4, 3). What is the shape of m.sum(axis=0)?

    axis=0 collapses the rows, leaving one total per column, and there are 3 columns.
  3. 3. Which line correctly keeps the values of a between 10 and 20?

    Masks combine with &, and each comparison needs parentheses because & binds more tightly than >.
  4. 4. You run part = data[:3] and then part[0] = 99. What happens to data?

    Array slices share memory with the original. Use .copy() for an independent array.
  5. 5. Why can a (3, 4) array be multiplied by an array of shape (4,) but not (3,)?

    The last dimensions are compared first. To scale each row, reshape the 3 values into a (3, 1) column.

Summary

  • NumPy's array stores values of one dtype side by side, which makes math on large datasets fast. Import it as np.
  • Create arrays with np.array(), arange(), linspace(), zeros(), ones() and a seeded default_rng() for random data.
  • shape, ndim and reshape() describe and change the layout; .T transposes.
  • Arithmetic, comparisons and ufuncs like np.sqrt work element-wise, no loop needed.
  • Index 2-D arrays with a[row, col]. Slices are views; use .copy() for independent data.
  • Filter with boolean masks, combined with &, | and ~ and wrapped in parentheses.
  • Broadcasting stretches dimensions of size 1 to combine different shapes; add a dimension with np.newaxis when needed.
  • Aggregates such as sum(), mean() and max() take an axis: 0 for per-column, 1 for per-row results.

Next: Pandas Basics, where you'll work with labeled tables of data built on top of NumPy arrays.