This is an archived version of the course. Please see the latest version of the course.

Creating arrays

Numpy provides you with different convenient functions to create special types of arrays.

These are mainly useful if you need to initialise an array and fill it up later.

You can create an array filled with zeros, ones, or a number of your choice.

x = np.zeros(3)
## [0. 0. 0.]

x = np.ones(3)
## [1. 1. 1.]

x = np.full(3, 10)
## [10 10 10]

x = np.zeros((2, 3))  # 2 rows, 3 columns
## [[0. 0. 0.]
##  [0. 0. 0.]]

x = np.ones((2, 3)) 
## [[1. 1. 1.]
##  [1. 1. 1.]]

x = np.full((2, 3), 9.)
## [[9. 9. 9.]
##  [9. 9. 9.]]

Or filled with random numbers.

x = np.empty((2,4))
## [[6.95333209e-310 1.93101617e-312 6.95333207e-310 6.91856305e-310]
##  [6.95333208e-310 2.12199579e-314 6.95333207e-310 6.95333213e-310]]

You can also create an identity matrix with either np.eye() or np.identity().

x = np.eye(3)
## [[1. 0. 0.]
##  [0. 1. 0.]
##  [0. 0. 1.]]

There is also a function np.arange(start, stop, step) that is equivalent to Python’s range().

x = np.arange(3, 11, 2)   ## [3 5 7 9]

If you use np.arange() with non-integer arguments, the results may not be consistent due to floating point precision issues. In such cases, it will be better to use np.linspace() to create an array with values that are spaced linearly in a specified interval.

# Generate an array with 5 elements, equally spaced between 0 to 10 
x = np.linspace(0, 10, num=5)  ## [ 0.   2.5  5.   7.5 10. ]

You can use np.zeros_like(arr), np.ones_like(arr), np.full_like(arr), and np.empty_like(arr) to create arrays of zeros, ones and random numbers of the same shape AND type as arr (arr can be an np.ndarray or a Python list).

x = np.array([[1,2,3], [3,4,5]])
print(x)
## [[1 2 3]
##  [4 5 6]]
print(x.shape)
## (2, 3)

y = np.zeros_like(x)
print(y)
## [[0 0 0]
##  [0 0 0]]
print(y.shape)
## (2, 3)

I have only highlighted some of the array creation functions that will likely be more useful. There are many other array creation functions that I will not cover (like creating from a file or a string). I will leave it to you to explore on your own by reading the documentation.