← Python for Data Analysis

PDA·04 · Chapter 4

NumPy Basics

Chapter 4 — arrays and vectorised computation

NumPy is what makes numerical Python fast, and pandas is built on it. Six sessions: the ndarray itself, slicing (and why slices are views), boolean masks, random numbers and ufuncs, replacing loops with array expressions, and a random walk that pulls it all together.

4.1

The ndarray

  • NumPy's ndarray is a grid of values that all share one type, stored in one block of memory. That is why it is fast: loops run in C, not in Python.
  • Operations apply to every element at once — no for loop. This is called vectorisation. Doubling a million numbers is roughly 10–100× faster than a list comprehension.
  • Every array has a shape (a tuple of sizes per dimension) and a dtype (the element type, such as float64 or int32).
  • Create arrays with np.array(list), np.zeros, np.ones, np.arange (like range), and change shape with reshape.
  • astype converts dtype and always makes a new array. Casting floats to ints truncates — it drops the decimals, it does not round.
ndarray
an n-dimensional array of one data type
Vectorisation
applying an operation to whole arrays without writing a loop
Shape
the size of each dimension, e.g. (2, 3)
dtype
the data type of every element, e.g. float64
astype
returns a copy converted to another dtype
import numpy as np

data = np.array([[1.5, -0.1, 3], [0, -3, 6.5]])
print(data * 10)
print(data.shape, data.dtype)

arr = np.array([3.7, -1.2, -2.6, 0.5, 12.9, 10.1])
print(arr.astype(np.int32))
print(np.arange(6).reshape((2, 3)))
[[ 15.  -1.  30.]
 [  0. -30.  65.]]
(2, 3) float64
[ 3 -1 -2  0 12 10]
[[0 1 2]
 [3 4 5]]
Activity 1

Time [x * 2 for x in range(1_000_000)] against np.arange(1_000_000) * 2 using %timeit in a notebook. How many times faster is NumPy on your machine?

Activity 2

Make a 3×4 array of the numbers 1 to 12 with arange and reshape. Print its shape, dtype, and the array divided by 2.