Generating Numerical Sequences
January 18, 2018
Generating Numerical Sequences
Numpy comes with in-built functions that allow us to easily generate numerical sequences.
Import Libraries
import numpy as np
arange
By default, arange
generates an ndarray
that begins at 0
and ends at n - 1
, with increments/steps of 1.
print(np.arange(5))
[0 1 2 3 4]
If we state a lower and upper limit, arange
generates an ndarray
that includes the lower limit, up to but not including the upper limit.
print(np.arange(0, 7))
[0 1 2 3 4 5 6]
We can also control the increment/step between each member of the sequence.
print(np.arange(0, 7, 2))
[0 2 4 6]
It is also possible to create a reverse-ordered sequence.
print(np.arange(4, -1, -1))
[4 3 2 1 0]
linspace
If we know the start, end, the number of samples and require an equally spaced list, the linspace
function will be more appropriate.
print(np.linspace(start=0, stop=20, num=5))
[ 0. 5. 10. 15. 20.]
zeros and ones
zeros
and ones
allow us to easily create single or multi-dimensional arrays that contains all 0s or 1s.
print(np.zeros(5))
[0. 0. 0. 0. 0.]
print(np.zeros([2, 3])) # 2 rows, 3 columns
[[0. 0. 0.]
[0. 0. 0.]]
print(np.ones(5))
[1. 1. 1. 1. 1.]
print(np.ones([3, 4])) # 3 rows, 4 columns
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]