Lesson 1 of 4
Meet NumPy, the foundation of numerical computing in Python: import it, create your first arrays, and calculate on whole datasets at once.
About 25 minutes
You have already used import math to load extra functions. A module is a single file of Python code; a package is a collection of modules; and library is the everyday word for a package that provides a set of tools. Python's real strength in science comes from libraries written by the community, and the most important of all is NumPy (Numerical Python).
NumPy provides the array: a fast, compact grid of numbers. Almost every scientific Python library, including Matplotlib, SciPy, pandas and the materials packages ASE and pymatgen, is built on NumPy arrays.
An introduction, not the whole story
NumPy is imported with a short alias. import numpy as np loads the library and lets you refer to it as np. This alias is a universal convention: you will see np. in almost all scientific Python code. The first time you run NumPy code here, it takes a few seconds to load.
import numpy as nptemperatures = np.array([293.0, 310.0, 350.0, 400.0])print(temperatures)print(type(temperatures))np.array() turns a list into an array. NumPy prints arrays without commas, and shows 293. as shorthand for 293.0. The type is ndarray, short for n-dimensional array.
Lists can hold numbers, but they weren't designed for maths. To convert every temperature in a list you need a loop. With an array, you write the calculation once and NumPy applies it to every element. This is called vectorised arithmetic.
import numpy as npcelsius_list = [20, 450, 850, 1050]# With a list: a loop is neededkelvin_list = []for temperature in celsius_list: kelvin_list.append(temperature + 273.15)print(kelvin_list)# With an array: one expressioncelsius = np.array(celsius_list)print(celsius + 273.15)+ means different things
+ joins two lists together: [1, 2] + [3, 4] is [1, 2, 3, 4]. For arrays, + adds element by element: np.array([1, 2]) + np.array([3, 4]) is [4 6].All the arithmetic operators work element by element, both between an array and a single number and between two arrays of the same length. NumPy also has its own versions of mathematical functions, such as np.sqrt(), np.exp() and np.log(), which work on whole arrays.
Calculate the density of five samples from their masses and volumes in one step.
import numpy as npmasses = np.array([26.98, 89.60, 45.10, 78.70, 193.2]) # gvolumes = np.array([10.0, 10.0, 10.0, 10.0, 10.0]) # cm³densities = masses / volumesprint(densities)NumPy has functions for the statistics you use every day. Each takes an array and returns a single number.
| Function | Returns |
|---|---|
np.mean(a) | Arithmetic mean |
np.median(a) | Median (middle value) |
np.std(a) | Standard deviation |
np.min(a), np.max(a) | Smallest and largest value |
np.sum(a) | Sum of all elements |
import numpy as nphardness = np.array([152, 160, 158, 149, 155]) # HVprint(f"Mean: {np.mean(hardness):.1f} HV")print(f"Median: {np.median(hardness):.1f} HV")print(f"Std: {np.std(hardness):.2f} HV")print(f"Range: {np.max(hardness) - np.min(hardness)} HV")Functions and methods
hardness.mean() is the same as np.mean(hardness). You will see both styles in other people's code.Choose an answer and press Check answer. You can retry as often as you like.