NumPy demo

This is a quick demo of some of the NumPy features that will be useful in CSC411.

Importing the modules we'll be using:

In [1]:
from numpy import *

(Note that the usual convention is to use something like import numpy as np and import matplotlib.pyplot as plt, but I personally prefer from numpy import *.)

NumPy uses the array data structure. The array data structure is an N-dimensional matrix of elements why are all of the same type.

In [2]:
a = array([5, 4, 10]) 
In [3]:
a
Out[3]:
array([ 5,  4, 10])

We can access individual elements of the array:

In [4]:
a[1]
Out[4]:
4
In [5]:
a[1:3]
Out[5]:
array([ 4, 10])

Here is how to make a 2D array:

In [6]:
a = array([[4,5,6], [1,2,3]])
In [7]:
a
Out[7]:
array([[4, 5, 6],
       [1, 2, 3]])

We can access elements of the 2D array like this:

In [8]:
a[1, 0]
Out[8]:
1

We can slices matrices like this:

In [9]:
a[:, 1]  #Get the second column
Out[9]:
array([5, 2])
In [10]:
a[:, 1:3]
Out[10]:
array([[5, 6],
       [2, 3]])

We can get the shape of the array using

In [11]:
a.shape
Out[11]:
(2, 3)