NumPy

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.

Library documentation: http://www.numpy.org/

from numpy import *
# declare a vector using a list as the argument
v = array([1,2,3,4])
v
# declare a matrix using a nested list as the argument
M = array([[1,2],[3,4]])
M
# still the same core type with different shapes
type(v), type(M)
M.size
# arguments: start, stop, step
x = arange(0, 10, 1)
x
linspace(0, 10, 25)
logspace(0, 10, 10, base=e)
x, y = mgrid[0:5, 0:5]
x
y
from numpy import random
random.rand(5,5)
# normal distribution
random.randn(5,5)
diag([1,2,3])
M.itemsize
M.nbytes
M.ndim
v[0], M[1,1]
M[1]
# assign new value
M[0,0] = 7
M
M[0,:] = 0
M
# slicing works just like with lists
A = array([1,2,3,4,5])
A[1:3]
A = array([[n+m*10 for n in range(5)] for m in range(5)])
A
row_indices = [1, 2, 3]
A[row_indices]
# index masking
B = array([n for n in range(5)])
row_mask = array([True, False, True, False, False])
B[row_mask]

Linear Algebra

v1 = arange(0, 5)
v1 + 2
v1 * 2
v1 * v1
dot(v1, v1)
dot(A, v1)
# cast changes behavior of + - * etc. to use matrix algebra
M = matrix(A)
M * M
# inner product
v.T * v
C = matrix([[1j, 2j], [3j, 4j]])
C
conjugate(C)
# inverse
C.I

Statistics

mean(A[:,3])
std(A[:,3]), var(A[:,3])
A[:,3].min(), A[:,3].max()
d = arange(1, 10)
sum(d), prod(d)
cumsum(d)
cumprod(d)
# sum of diagonal
trace(A)
m = random.rand(3, 3)
m
# use axis parameter to specify how function behaves
m.max(), m.max(axis=0)
A
# reshape without copying underlying data
n, m = A.shape
B = A.reshape((1,n*m))

B
# modify the array
B[0,0:5] = 5
B
# also changed
A
# creates a copy
B = A.flatten()
B
# can insert a dimension in an array
v = array([1,2,3])
v[:, newaxis], v[:,newaxis].shape, v[newaxis,:].shape
repeat(v, 3)
tile(v, 3)
w = array([5, 6])
concatenate((v, w), axis=0)
# deep copy
B = copy(A)