NumPy Array Factory Functions
Introduction
Welcome back to From Lists to Arrays. We are at lesson 5, where we will create NumPy arrays without first building a Python list. These tools are called factory functions: each one generates an array for a particular purpose. We will make integer sequences, evenly spaced points, and arrays filled with values such as zeros, ones, or a chosen placeholder. By the end, we will know what each function creates and what dtype to expect.
Generating Integer Ranges with np.arange
When we need a sequence of integers, np.arange can create it directly. Give it a starting value, a stopping value, and an optional step size. The starting value is included, but the stopping value is not. Here, we generate hour marks from 0 up to, but not including, 12, moving forward by 2 each time. As always, we import NumPy as np first; the later snippets continue from this setup.
The arguments mean “start at 0, stop before 12, and count by 2.” The printed array contains six values:
This is useful when we know the step between values, such as when marking every two hours. We can create the array without writing a source list first.
Evenly Spaced Points with np.linspace
Sometimes we know the endpoints and the number of points we want, rather than the step between points. For that, we can use np.linspace. It includes both endpoints by default and spaces the requested number of values evenly across the interval. Here, the interval from 0 to 1 is divided into five points.
The third argument, 5, is the number of values to generate. Because both endpoints are included, the four gaps between the five points are equal. The output shows quarter steps:
Use np.arange when the step size is the key detail; use np.linspace when the number of evenly spaced points is the key detail.
Constant Arrays with np.zeros and np.ones
We can also create an array whose entries all start with the same value. np.zeros fills the array with zeros, while np.ones fills it with ones. The number inside the parentheses sets the length of the one-dimensional array. For example, zeros can represent an empty week of counts, and ones can represent a simple baseline.
This creates seven entries without listing each one. The printed result is:
We will create the four-value baseline with np.ones in the next example, alongside a check of the zeros array’s dtype.
