Sub topic 2
Creating arrays
This chapter assumes you know basic Python (lists, loops, functions) and can run code in a script or notebook. It also assumes you know roughly what vectors and matrices are. Creating arrays is the first step before indexing, broadcasting, or any computation.
From Python sequences
np.array builds an array from a list or nested lists. NumPy looks at the values, picks one dtype for all of them, and measures the nesting depth to get the shape.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape) # (2, 3)
print(a.ndim) # 2
print(a.size) # 6
print(a.dtype) # int64 on most 64-bit Linux and macOS systemsThe nested lists must be rectangular. If the inner lists have different lengths, NumPy raises a ValueError instead of building a ragged array.
Functions that generate arrays
Writing out every value is rarely practical. NumPy has functions that build common arrays directly.
| Function | What it produces |
|---|---|
| `np.zeros(shape)` | Array filled with `0.0` |
| `np.ones(shape)` | Array filled with `1.0` |
| `np.full(shape, value)` | Array filled with `value` |
| `np.arange(start, stop, step)` | Evenly spaced values, stop excluded |
| `np.linspace(start, stop, num)` | `num` evenly spaced values, stop included |
import numpy as np
print(np.zeros((2, 3))) # 2x3 array of 0.0
print(np.arange(0, 10, 2)) # [0 2 4 6 8]
print(np.linspace(0, 1, 5)) # [0. 0.25 0.5 0.75 1. ]
print(np.array([1.7, 2.9]).astype(np.int64)) # [1 2], values are truncatedThe last line shows that astype converts the dtype and truncates floats toward zero. It does not round. astype returns a new array, so the original is unchanged.
Choosing between arange and linspace
Both produce evenly spaced numbers, but they take different inputs.
- Use
arangewhen you know the step size. The stop value is excluded, as withrange. - Use
linspacewhen you know how many points you need. The stop value is included by default.
With a float step, arange can give a surprising number of elements because of rounding error. For example, np.arange(0, 1, 0.1) is usually fine, but a step like 0.3 can add or drop the last element depending on rounding. When you need an exact count, linspace is the safer choice.
Controlling the dtype
Every creation function accepts a dtype argument. Setting it at creation avoids a later conversion and makes your intent clear.
import numpy as np
counts = np.zeros(3, dtype=np.int32)
print(counts.dtype) # int32
mixed = np.array([1, 2.5, 3])
print(mixed.dtype) # float64, the ints were upcastWhen a list mixes integers and floats, NumPy picks a type that can hold all of them. Here that is float64.
Common errors
- Passing a bare number as the shape.
np.zeros(3)works and gives shape(3,). For two or more dimensions, pass a tuple:np.zeros((2, 3)). Writingnp.zeros(2, 3)makes3the dtype argument and raises aTypeError. - Ragged lists.
np.array([[1, 2], [3]])raises aValueError. Make the rows the same length, or keep a list of arrays. - Expecting
arangeto include the stop value. It does not. Uselinspaceif you need the endpoint. - Assuming integer output from
zeros.np.zerosreturns floats unless you setdtype.
Exercise
You need exactly 11 evenly spaced values from 0 to 1, including both endpoints. Which call do you use, and why is np.arange a poor fit here?
Show answer
Use np.linspace(0, 1, 11). It takes the number of points and includes the endpoint. np.arange takes a step, excludes the stop value, and with a float step such as 0.1 rounding error can change how many elements you get.
Exercise
What does np.array([2.9, -2.9]).astype(np.int64) return, and why?
Show answer
It returns [2, -2]. astype truncates floats toward zero instead of rounding, so 2.9 becomes 2 and -2.9 becomes -2.