Lesson 03
Creating Arrays
Build arrays without typing every value: arange, zeros, ones, full, linspace, identity, eye, and joining arrays with hstack and vstack.
Typing every value into np.array does not scale. NumPy has functions that build an array from a rule: a range, a fill value, an even spacing, or a diagonal. Shapes are passed as a tuple, such as (2, 3).
arange and reshape
np.arange works like range but returns an array. Give it a stop, or a start and a stop, or a start, a stop, and a step. The stop is not included. The step can be a float. Chain reshape to lay the values out in rows.
import numpy as np
print(np.arange(5))
print(np.arange(2, 8))
print(np.arange(10, 0, -3))
print(np.arange(0, 1, 0.25))
print(np.arange(12).reshape(3, 4))Output:
[0 1 2 3 4]
[2 3 4 5 6 7]
[10 7 4 1]
[0. 0.25 0.5 0.75]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]zeros, ones, and full
These fill a shape with one value. zeros and ones give floats unless you pass a dtype. full takes the shape and the fill value.
import numpy as np
print(np.zeros(3))
print(np.ones((2, 3), dtype=int))
print(np.full((2, 2), 7))Output:
[0. 0. 0.]
[[1 1 1]
[1 1 1]]
[[7 7]
[7 7]]linspace
np.linspace(start, stop, num) gives num evenly spaced values and includes the stop. num is 50 if you leave it out. Pass endpoint=False to leave the stop out, or retstep=True to also get the gap between values.
import numpy as np
print(np.linspace(0, 1, 5))
print(np.linspace(0, 1, 5, endpoint=False))
values, gap = np.linspace(10, 20, 3, retstep=True)
print(values, gap)Output:
[0. 0.25 0.5 0.75 1. ]
[0. 0.2 0.4 0.6 0.8]
[10. 15. 20.] 5.0identity and eye
np.identity(n) is a square grid with ones on the main diagonal. np.eye(rows, cols, k) can be rectangular, and k moves the diagonal right when positive or left when negative.
import numpy as np
print(np.identity(3, dtype=int))
print(np.eye(3, 4, k=1, dtype=int))
print(np.eye(3, k=-1, dtype=int))Output:
[[1 0 0]
[0 1 0]
[0 0 1]]
[[0 1 0 0]
[0 0 1 0]
[0 0 0 1]]
[[0 0 0]
[1 0 0]
[0 1 0]]hstack and vstack
hstack joins arrays side by side. vstack stacks them as rows. Both take one tuple of arrays, so note the extra parentheses.
import numpy as np
left = np.array([1, 2, 3])
right = np.array([4, 5, 6])
print(np.hstack((left, right)))
print(np.vstack((left, right)))Output:
[1 2 3 4 5 6]
[[1 2 3]
[4 5 6]]Key takeaways
-
arangeleaves the stop out, andlinspacekeeps it in -
Shapes are tuples:
np.zeros((2, 3)) -
eyewithkshifts the diagonal -
hstackandvstacktake a tuple of arrays -
Next: Random Arrays
-
Previous: Array Attributes
Loading playground…
Check your understanding
Creating Arrays Quiz
What does np.arange(2, 8) give?
1 / 10