{:check ["true"]}
Numpy is a Python library, so it comes as a collection of Python modules.
import numpy
import numpy.random
import numpy.linalg
ndarray
stands for n-dimensional arrays. They are the fundamental data structure in numerical data processing.
# This is a Python list.
data1 = [6, 7, 8, 0., 1.]
Working with Python list is easy, but cumbersome. Suppose each element is a radius of some circle, and we want to generate a list of areas.
areas = []
for r in data1:
areas.append(3.1415 * r * r)
areas
Even with list comprehension, it's not that pretty:
[3.1415 * r * r for r in data1]
Numpy can take care of this type of mathematical operations on ndarray much nicer and faster.
arr1 = numpy.array(data1)
arr1
3.1415 * arr1 ** 2
Let's start with a nested Python list. Note that it describes a 2D matrix, but with Python lists.
data2 = [[1,2,3,4],
[5,6,7,8]]
We can convert it to a 2D nd-array.
arr2 = numpy.array(data2)
arr2
# Number of dimensions
arr2.ndim
# Number of entries in each dimension
arr2.shape
# What is the datatype of each element in `arr2`?
arr2.dtype
import numpy as np
#
# Create a nd-array of zeros
#
np.zeros(5)
np.zeros((5,5))
#
# Let's create some ones in different ways
#
np.ones((5,5))
np.zeros((5,5)) + 1
#
# We can create the identity matrix as a square 2D-array
#
np.eye(5)
#
# We can generate range as an array
#
np.arange(10)
#
# We can create a sequence of numbers
# that are evenly spaced between two points.
#
np.linspace(0, 1, 10)