Sub topic 2
Creating arrays
This chapter assumes you know basic Python (lists, loops, functions) and can import a library. It also assumes you know what shape, ndim and dtype mean on an ndarray. Here you learn the main ways to build arrays and what each one does to shape and dtype. Many shape and dtype surprises later in this tutorial begin at construction, so it pays to be exact now.
Choosing a constructor
Pick the constructor by the data you already have.
From existing Python data
np.array converts a sequence into an array. Nested lists become extra dimensions, and the nesting must be rectangular.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.shape, a.ndim, a.dtype) # (2, 3) 2 int64
b = np.array([1, 2.5, 3])
print(b.dtype) # float64
c = np.array([1, 2, 3], dtype=np.float32)
print(c.dtype) # float32The default integer type is int64 on most platforms. It can differ on others, so set dtype yourself if the width matters.
How dtype is chosen
An array has one dtype for all its elements. When you give it mixed Python numbers, NumPy picks the smallest type that holds them all. Integers mixed with floats give float64. Booleans mixed with integers give integers. If you pass dtype=, NumPy converts every element to that type. Converting to a narrower type can truncate silently: np.array([1.9, 2.7], dtype=int) gives [1 2], not [2 3].
Ragged input
A list of lists with different lengths has no rectangular shape. Current NumPy versions refuse to guess.
import numpy as np
try:
np.array([[1, 2], [3]])
except ValueError as err:
print("error:", type(err).__name__) # error: ValueError
obj = np.array([[1, 2], [3]], dtype=object)
print(obj.shape, obj.dtype) # (2,) objectAn object array holds references to Python objects. It gives up the speed and memory benefits of NumPy, so treat it as a last resort. Usually the better fix is to pad the data or store the pieces in separate arrays.
array versus asarray
np.array copies its input by default. np.asarray returns the input unchanged if it is already an array of the right dtype, and converts otherwise.
import numpy as np
x = np.arange(3)
y = np.asarray(x) # no copy: same object
z = np.array(x) # copy
print(y is x) # True
print(z is x) # False
print(np.shares_memory(x, y)) # True
print(np.shares_memory(x, z)) # FalseUse asarray at the top of a function that accepts "array-like" input (lists, tuples, arrays). It avoids a needless copy when the caller already passed an array. The cost is that your function may then modify the caller's data if you write into the result. Use np.array(x) when you need an independent copy.
Arrays of a known shape
When you know the shape but not yet the values, ask for the shape directly. The shape is a tuple. Passing a bare integer gives a 1-D array.
import numpy as np
print(np.zeros((2, 3)))
# [[0. 0. 0.]
# [0. 0. 0.]]
print(np.ones(3)) # [1. 1. 1.]
print(np.full((2, 2), 7)) # integer fill gives an integer array
# [[7 7]
# [7 7]]
print(np.full((2, 2), 7.0).dtype) # float64zeros, ones and empty default to float64. np.full takes its dtype from the fill value. That makes np.full((2, 2), 7) an integer array, which then silently truncates if you later assign 0.5 into it. Pass dtype=float when you want floats.
np.empty allocates memory without writing anything to it. The contents are whatever bytes were there before, so printing an empty array can show arbitrary numbers.
Matching an existing array
The _like functions copy shape and dtype from another array: np.zeros_like, np.ones_like, np.empty_like and np.full_like.
import numpy as np
a = np.arange(6).reshape(2, 3)
z = np.zeros_like(a)
f = np.full_like(a, 9)
print(z.shape, z.dtype) # (2, 3) int64
print(f)
# [[9 9 9]
# [9 9 9]]Since a is an integer array, z and f are integer arrays too. If you need floats, pass dtype=float, for example np.zeros_like(a, dtype=float).
Ranges of numbers
np.arange(start, stop, step) works like Python's range. It includes start, excludes stop, and returns an array. np.linspace(start, stop, num) returns exactly num evenly spaced values and, by default, includes stop.
import numpy as np
print(np.arange(5)) # [0 1 2 3 4]
print(np.arange(2, 10, 3)) # [2 5 8]
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.linspace(0, 1, 4, endpoint=False)) # [0. 0.25 0.5 0.75]The two functions answer different questions:
| Function | You specify | Length is | Endpoint |
|---|---|---|---|
| `np.arange` | step size | computed from the step | excluded |
| `np.linspace` | number of points | exactly what you asked | included by default |
Why arange with float steps is risky
With a float step, the length is computed as ceil((stop - start) / step). Rounding error in that division can add or drop the last element, and which one depends on the numbers. The NumPy documentation recommends linspace for non-integer steps. Use arange for integers, and linspace whenever the count or the endpoint matters.
Combining arange with reshape
np.arange(n).reshape(r, c) is a quick way to make a test matrix with distinct values. The product of r and c must equal n. You can also build axes for broadcasting this way. np.arange(3).reshape(3, 1) is a column, which you will combine with a row in the broadcasting chapters.
Special matrices
np.eye(n) makes an n by n identity matrix, with ones on the diagonal and zeros elsewhere. np.identity(n) does the same with fewer options. np.eye accepts a column count and a diagonal offset k.
import numpy as np
print(np.eye(3))
# [[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]
print(np.eye(2, 3, k=1))
# [[0. 1. 0.]
# [0. 0. 1.]]np.diag builds a diagonal matrix from a 1-D array. It extracts the diagonal when given a 2-D array.
Random arrays
Create a generator object with np.random.default_rng, then call its methods. Passing a seed makes the sequence repeatable, which is useful in tests and tutorials.
import numpy as np
rng = np.random.default_rng(seed=42)
u = rng.random((2, 3)) # floats in [0, 1)
k = rng.integers(0, 10, size=5) # integers from 0 to 9
n = rng.normal(loc=0.0, scale=1.0, size=(2, 2))
print(u.shape, u.dtype) # (2, 3) float64
print(k.shape) # (5,)
print(n.shape) # (2, 2)
rng2 = np.random.default_rng(seed=42)
print(np.array_equal(rng2.random((2, 3)), u)) # Truerng.integers(low, high) excludes high by default. The older global functions such as np.random.rand still work, but they share one hidden state across your program. A generator you create and pass around is easier to reason about and test.
Common mistakes
- Forgetting the tuple.
np.zeros(2, 3)fails because the second positional argument isdtype. Writenp.zeros((2, 3)). - Integer arrays that truncate. An array created from integers, such as
np.array([1, 2, 3])ornp.arange(3), stores integers. Assigning0.7into it stores0. Build it withdtype=floatif you plan to store fractions. - Assuming
np.arrayshares memory. It copies. If you want a view of existing data, useasarrayor slicing, which the next chapter covers. - Reading from
np.empty. The values are leftover memory, not zeros. - Float steps in
arange. The length can be off by one. Uselinspace. - Building arrays by appending in a loop.
np.appendcopies the entire array each call. Collect values in a Python list and convert once, or preallocate withnp.zerosand fill.
Summary
Use np.array or np.asarray for existing data, and remember that only array copies. Use zeros, ones, full and empty when you know the shape, and pay attention to the dtype each one picks. Use arange for integer steps and linspace for a fixed count of points. Use eye for identity matrices and default_rng for random values.
Exercise
You run m = np.full((2, 2), 3) and then m[0, 0] = 2.9. What does m[0, 0] hold afterwards, and what single change to the first line avoids the problem?
Show answer
It holds 2. np.full takes its dtype from the fill value 3, so the array is an integer array, and assigning 2.9 truncates it. Pass a float fill value or a dtype, for example np.full((2, 2), 3.0) or np.full((2, 2), 3, dtype=float).
Exercise
Write one expression that produces a column of shape (4, 1) containing the integers 0 through 3, and one that produces 6 evenly spaced floats from 0 to 1 inclusive. State the shape you expect from each.
Show answer
np.arange(4).reshape(4, 1) has shape (4, 1). np.linspace(0, 1, 6) has shape (6,) with values 0, 0.2, 0.4, 0.6, 0.8 and 1.0. Using linspace fixes the count at 6 and includes the endpoint, which arange with a float step does not guarantee.