Sub topic 2
Creating arrays
This chapter assumes you know what shape, ndim and dtype mean (from the previous chapter) and can run Python code that imports NumPy. You will learn the main ways to build an array and how each one decides the shape and dtype.
Arrays from Python data
np.array converts a list, or a list of lists, into an ndarray. Nesting depth sets ndim, and the length of each level sets shape.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape, a.dtype) # (2, 3) int64 on most platforms
b = np.array([1, 2.5])
print(b.dtype) # float64
c = np.array([1, 2, 3], dtype=np.float32)
print(c.dtype) # float32NumPy picks one dtype for the whole array. Mixing integers and floats gives floats. Pass dtype= when you need a specific type, such as float32 to save memory.
The inner lists must all have the same length. A ragged input such as [[1, 2], [3]] raises a ValueError in current NumPy versions, unless you ask for dtype=object, which gives up fast numeric operations.
Arrays with a fixed pattern
When you know the shape but not the data, use a filling function. Each takes the shape as a tuple.
import numpy as np
print(np.zeros((2, 3))) # 2x3 of 0.0
print(np.ones(3)) # [1. 1. 1.]
print(np.full((2, 2), 7)) # 2x2 of 7
print(np.eye(3)) # 3x3 identity matrixzeros, ones and eye default to float64. full takes its dtype from the fill value, so np.full((2, 2), 7) is an integer array.
np.empty(shape) allocates memory without writing to it. The contents are whatever was already there, so use it only when you will overwrite every element.
To copy the shape and dtype of an existing array, use the _like variants: np.zeros_like(a), np.ones_like(a), np.full_like(a, 9) and np.empty_like(a).
Arrays from ranges
np.arange is like Python's range but returns an array and accepts float steps. np.linspace instead fixes the number of points.
import numpy as np
print(np.arange(0, 10, 3)) # [0 3 6 9]
print(np.arange(0, 1, 0.25)) # [0. 0.25 0.5 0.75]
print(np.linspace(0, 1, 5)) # [0. 0.25 0.5 0.75 1. ]
print(np.arange(12).reshape(3, 4).shape) # (3, 4)The two functions treat the endpoint differently:
| Function | You give | Endpoint included? |
|---|---|---|
| `np.arange(start, stop, step)` | the step size | No, the stop value is excluded |
| `np.linspace(start, stop, num)` | the number of points | Yes, by default |
Chaining .reshape onto arange, as in the last line above, is the quickest way to get a test array of any shape. The total size must match: 12 elements can become (3, 4), (2, 6) or (2, 2, 3).
Random arrays
For random data, create a generator once and call its methods. Seeding it makes results repeatable.
import numpy as np
rng = np.random.default_rng(0)
u = rng.random((2, 3)) # uniform values in [0, 1)
n = rng.normal(size=(2, 3)) # standard normal values
k = rng.integers(0, 10, size=4) # integers from 0 to 9
print(u.shape, n.shape, k.shape) # (2, 3) (2, 3) (4,)default_rng is the current interface. Prefer it over the older np.random.rand family, because the generator object has its own state and does not share a hidden global seed.
Choosing a constructor
Exercise
What does np.linspace(0, 1, 5) return, and how does that differ from np.arange(0, 1, 0.25)?
Show answer
linspace returns 5 values, [0. 0.25 0.5 0.75 1.], and includes the endpoint 1. arange returns 4 values, [0. 0.25 0.5 0.75], because it excludes the stop value.
Exercise
You have an array a with shape (4, 5) and dtype int64. Write one expression that makes an array of zeros with the same shape and dtype.
Show answer
np.zeros_like(a)