{:check ["true"]}

Index

Creating NDArrays

Create1

Numpy is a Python library, so it comes as a collection of Python modules.

In [1]:
import numpy
import numpy.random
import numpy.linalg

Creating ndarrays

ndarray stands for n-dimensional arrays. They are the fundamental data structure in numerical data processing.

In [3]:
# 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.

In [4]:
areas = []
for r in data1:
    areas.append(3.1415 * r * r)
areas
Out[4]:
[113.094, 153.9335, 201.056, 0.0, 3.1415]

Even with list comprehension, it's not that pretty:

In [6]:
[3.1415 * r * r for r in data1]
Out[6]:
[113.094, 153.9335, 201.056, 0.0, 3.1415]

Numpy can take care of this type of mathematical operations on ndarray much nicer and faster.

In [11]:
arr1 = numpy.array(data1)
arr1
Out[11]:
array([6., 7., 8., 0., 1.])
In [12]:
3.1415 * arr1 ** 2
Out[12]:
array([113.094 , 153.9335, 201.056 ,   0.    ,   3.1415])

Two dimensional ndarrays

Let's start with a nested Python list. Note that it describes a 2D matrix, but with Python lists.

In [16]:
data2 = [[1,2,3,4],
         [5,6,7,8]]

We can convert it to a 2D nd-array.

In [18]:
arr2 = numpy.array(data2)
arr2
Out[18]:
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
In [19]:
# Number of dimensions
arr2.ndim
Out[19]:
2
In [21]:
# Number of entries in each dimension
arr2.shape
Out[21]:
(2, 4)
In [22]:
# What is the datatype of each element in `arr2`?
arr2.dtype
Out[22]:
dtype('int64')

Create2

In [2]:
import numpy as np

More functions to create nd-arrays

In [3]:
#
# Create a nd-array of zeros
#
np.zeros(5)
Out[3]:
array([0., 0., 0., 0., 0.])
In [4]:
np.zeros((5,5))
Out[4]:
array([[0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.]])
In [5]:
#
# Let's create some ones in different ways
#
In [6]:
np.ones((5,5))
Out[6]:
array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])
In [7]:
np.zeros((5,5)) + 1
Out[7]:
array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])
In [8]:
#
# We can create the identity matrix as a square 2D-array
#
np.eye(5)
Out[8]:
array([[1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 1.]])
In [9]:
#
# We can generate range as an array
#
np.arange(10)
Out[9]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [10]:
#
# We can create a sequence of numbers 
# that are evenly spaced between two points.
#
np.linspace(0, 1, 10)
Out[10]:
array([0.        , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
       0.55555556, 0.66666667, 0.77777778, 0.88888889, 1.        ])