numpy
¶This is a quick tour of some numpy
features. For more detail see:
Every section of this document can be run independently of the others, except the first one (which imports the module). Within a section, cells often require the ones before them to be run.
None of the code below will work without this!
import numpy as np
np.__version__
# all zeros, specified shape
np.zeros( (2,3) )
# all ones, specified shape
np.ones( (8,) )
# array with every entry equal to a given constant
np.full( (3,3), 1.7 ) # shape, value
A = np.ones( (4,4) )
A.ndim # the dimension of A
A.shape # the shape of A
A.size # the number of elements in A
A.dtype # the data type (np.ones gives float64 by default)
B = np.full( (2,3), 6 ) # Python int given, converted to int64
B.dtype
# Build array from an iterable
C = np.array( [[5,6,7,8],[9,10,11,12]] )
print(C.ndim)
print(C.dtype)
print(C.size)
# np.random.random(shape) gives array of uniformly distributed
# random floats 0<=x<1
np.random.random((5,8))
np.ones((2,2),dtype="bool") # numpy supports boolean arrays
# coerces 0 to False and 1 to True
Abyte = np.zeros((4,3),dtype="uint8") # Array of 1-byte values
Abyte
Abyte[1,1] = 10
Abyte[3,2] = 300
Abyte
A = np.random.random((3,2))
A
np.zeros_like(A)
np.arange(3,8,0.7) # start, stop, step. Will not include stop.
np.linspace(2,7,31) # first, last, num_steps
A = np.array(range(24)).reshape((4,6)) # 0..23 in a vector, but then convert to 4x6 matrix
v = np.arange(1,5,1.2) # vector (array with ndim=1)
A
v
v[1] # element at index 1 (zero-based)
v[-2] # second to last element
A[2,0] # row 2, column 0
A[:,2] # column 2 of A (remember, 0-based numbering!)
# I think of this as A[anything,2]
A[1,:] # row 1 of A
# I think of this as A[1,anything]
A[1] # another way to specify row 1 of A
# missing indices are treated as ":"
A[::2,1:3] # all rows of even index, columns 1 and 2
A = np.zeros((5,3))
A
A[2,1] = 64
A
A[1] = np.random.random(3)
A
B = np.full((9,9),2,dtype="float")
B
B.dtype
B[::3,::3] = np.random.random((3,3))
B
C = np.zeros((4,4))
X = C[1:3,1:3]
C
X # is a view of part of C, not a copy
X[0,0] = 51
X
C
Y = X.copy()
Y[1,1] = 88
Y
X
Vectors are 1D arrays
v = np.array([1.5,2.5,1])
v
w = np.array([-0.5,3,0])
w
2.1*v # elementwise multiplication
v+w
v*w # There's a good chance this isn't what you want.
v.dot(w)
Matrices are 2D arrays
M = np.eye(3)
M
M[1] = np.linspace(10,20,3)
M
6*M
M.T # transpose reverses the order of the axes; M.T[j,k] is M[k,j]
# Let's make an array to work with
A = np.array(range(1,16)).reshape((3,5))
A
1 / A # reciprocal of each entry in the matrix
A**2 # square of each entry
np.sin(A) # apply sin() to each entry
# first 11 cubes
np.arange(1,12)**3 # make vector of 1..11 and then cube each entry
If a higher-dimensional array is needed for an operation, produce one by duplication.
A = np.full((3,4),5,dtype="float")
A[1] = 11
A
5+A
v = np.array( [1,2,3,4], dtype="float")
v
A + v # add v to each row of A
# 3x4 (3x)4
B = np.zeros( (6,6) )
B[::2,1:5] = 7
B
A = np.arange(1,10).reshape((3,3))
A
B = np.array( [ [10,20,30], [19,23,56]])
B
C = np.array( [ [2,1], [1,1] ])
C
np.vstack([A,A])
np.hstack([A,A])
v = np.arange(15)
v
np.sum(v)
np.max(v)
np.mean(v)
np.all(v) # are all of the elements True / nonzero?
np.any(v) # is there at least one True / nonzero element
Suppose we want to consider a rectangular grid of points in the plane. Numpy has a function to take a list of x values, a list of y values, and then return all possible pairs of x and y from these lists in a convenient form.
x = np.linspace(-1,1,11)
x
y = np.linspace(0,2,6)
y
xx,yy = np.meshgrid(x,y) # will return two len(y) x len(x) arrays
# xx will be constant along columns (values from x along rows)
# yy will be constant along rows (values from y along columns)
xx
yy
# A is the sum of two matrices:
# 4x4 zeros, add [0,1,2,3] to each row, take the transpose
# 4x4 zeros, add [0,2,4,6] to each row
A = (np.zeros((4,4))+np.arange(4)).T + (np.zeros((4,4))+np.arange(0,8,2))
# -3 to 3
v = np.arange(-3,4)
w = np.array([-2,-2,0,0,4,5,5])
A
v
w
v==w
v>w
v<w
A == np.zeros((4,4))
A
mask = np.array( [True, True, False, False, False, True, False])
mask.dtype
v
v[mask] # 1D array of all the entries in v where mask is True
mask2d = np.zeros((4,4),dtype="bool")
mask2d[0,0] = True
mask2d[2,3] = True
mask2d
A[mask2d]
v
mask
v[mask] = 275
v
# -3 to 3
v = np.arange(-3,4)
v
v[mask]+=1
# v[mask] = v[mask] + 1
# ^^^^^^^^^^^ broadcasting
v
v[v<0] = 0
v
A
A[A%2==0] = 42
A
np.any(A<0) # Does A have any entries that are negative?