NUMPY:Why NumPy, and how to install it

Mastering why numpy, and how to install it concepts and implementation.

The hook

A Python list of a million numbers is a row of boxes, and each box holds a full Python object. Adding two such lists with a for loop walks those boxes one by one. NumPy stores the numbers in one contiguous block and runs the arithmetic in compiled code. The same addition is often 10 to 100 times faster, and the line that does it is shorter than the loop.

This course assumes you can write variables, lists, and for loops. If those still feel new, finish the Python course first, then come back.

Install

NumPy is not part of the Python standard library. In a terminal:

pip install numpy

Check the install:

import numpy as np

print(np.__version__)

Output:

2.1.0

The version number on your machine can differ. What matters is that import numpy does not raise ModuleNotFoundError.

In this site's data analysis lab, NumPy is already loaded. You do not install anything to practice there.

The first array

import numpy as np

scores = np.array([18, 21, 19, 24, 22])
print(scores)
print(scores * 2)

Output:

[18 21 19 24 22]
[36 42 38 48 44]

scores * 2 multiplied every element. A Python list would have repeated the list twice ([18, 21, ...] * 2). That single difference is why data code uses arrays.

What to notice

  • Import NumPy as np. Every example in this course, and almost every example you will read elsewhere, uses that name.
  • np.array copies the numbers into a typed block. After that, the array does not behave like a list.
  • Printing an array has no commas. That is a clue you are looking at an array, not a list.

Try this

Build an array of five temperatures in Celsius and convert them with c * 9 / 5 + 32. You should not write a loop.

Next: how arrays store a shape and a dtype, and why that matters when a column of integers silently becomes floats.