NTDS'17 demo 3: Numpy

Hermina Petric Maretic, EPFL LTS4

NumPy is the fundamental package for scientific computing with Python. It contains among other things:

  • a powerful N-dimensional array object
  • sophisticated (broadcasting) functions
  • tools for integrating C/C++ and Fortran code
  • useful linear algebra, Fourier transform, and random number capabilities

Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases.


In [ ]:
import numpy as np

In [ ]:
#create a numpy array
a = np.array([1,2,3,4])
a

In [ ]:
#or a 2 dimensional array
m = np.array([[1,2],[3,4]])
m

In [ ]:
m[0,0]

In [ ]:
m[:,1]

In [ ]:
a[:2]

In [ ]:
a[-2] #second last element of the array

In [ ]:
a[-2:] #last two elements of the array

Careful if you're used to Python list


In [ ]:
b = [1,2,3,4]

In [ ]:
b + b
b

In [ ]:
a + a
a

In [ ]:
#if you want to add elements to a
np.append(a,a)

In [ ]:
np.append(a,[1,2,3])

In [ ]:
np.insert(a, 1, 5) #insert 5 on position number 1

Basic arithmetics with numpy arrays


In [ ]:
a + 3

In [ ]:
a * 3

In [ ]:
a ** 3

In [ ]:
a * a

In [ ]:
a.sum()

In [ ]:
m * m #still elementwise multiplication

In [ ]:
np.dot(m,m) #standard matrix multiplication

In [ ]:
m = np.matrix(m) #there is a type matrix
m * m #for matrices, multiplication works as we're used to

Some functions to create arrays


In [ ]:
x = np.arange(0,10,2) #beginning, end, step
x

In [ ]:
np.linspace(0,10,5) #beginning, end, number of variables

In [ ]:
np.logspace(0,10,10,base=2) #beginning, end, number of variables

In [ ]:
np.diag([1,2,3])

In [ ]:
np.zeros(5)

In [ ]:
np.ones((3,3))

In [ ]:
np.random.rand(5,2)

Some linear algebra functions


In [ ]:
np.diag(m)

In [ ]:
np.trace(m)

In [ ]:
m.T

In [ ]:
m1 = np.linalg.inv(m)
m1

In [ ]:
np.linalg.det(m)

In [ ]:
np.linalg.det(m1)

In [ ]:
[eival, eivec] = np.linalg.eig(m)

In [ ]:
eival

In [ ]:
eivec