NumPy Examples
Given in cm3015 Topic 01: Introduction, Lab 3
To create a NumPy array from list:
data1D = [6, 7, 8]
data1DnD = np.array(data1D)
print(data1D)
print(data1DnD)
To print useful properties of our array:
print(data1DnD.shape)
print(data1DnD.ndim)
print(data1DnD.dtype)
To change the type of elements:
data1DnD_float = data1DnD.astype(np.float)
data1DnD_string = data1DnD.astype(np.string_)
For array indexing:
print(a[0]) #return the first element of ndarray a
print(a[:]) #return all the elements of ndarray a
print(a[-1]) #return the last element of ndarray a
print(a[:-1]) #return everything up to the last element
print(a[:-2]) #return everything up to the second last element
print(a[-2]) #return the second last element
There are various ways of creating an ndarray:
a = np.array([1, 2, 3])
b = np.zeros((1,5)) # Create an array of all zeros
c = np.ones((1,5)) # Create an array of all ones
d = np.full((1,5), 7) # Create an array filled with value 7
e = np.random.random((1,4)) # Create an array filled with random values
f = np.eye(3) # Create a 3x3 identity matrix (2D array)
g = np.ones((3,3,3)) # 3-Dimensional array
As the name suggests, an n-dimensional array can be generalised to multiple dimensions:
A=np.array([ [1,2], [3,4] ]) # Create a 2-D array (Matrix)
print(A[0,1]) # return the element on first column, second row (0,1)=2
We can reshape a vector (for example, v=[v1,v2,…,vN]) to a matrix of N1 x N2 dimensions (where N1xN2 = N). This is particularly useful for plotting images. As an example using numpy’s reshape method:
A = np.array([1,2,3,4,5,6]) # a 1D array
B = np.reshape( A, [2,3] ) # reshape as a 2D array with 2 rows and 3 columns
print(B)
To find indices that match a condition use np.where
Y = np.array([0, 1, 0, 1,1, 2,0,1,0])
one_indices = np.where(Y==1) # returns an array of in the indices matching the condition
To split an array into multiple sub-arrays use np.array_split
Y_split = np.array_split(Y, 3) # split into three arrays, does not have to equally divide the input array
To sort an array use np.sort to find the indices that sort the array use np.argsort
D = np.array([10,5,2,9,20,0,1])
D_sorted = np.sort(D) # returns a sorted copy [ 0 1 2 5 9 10 20]
sort_i = np.argsort(D) # returns an array of the indices in sorted order [5 6 2 1 3 0 4]
To concatenate arrays use np.concatenate. Takes an axis
argument which is the axis to concatenate on (default is 0)
Alternatively you can use the shorthand hstack or vstack (or dstack for 3D arrays):
X = np.random.random((2,2))
Y = np.random.random((2,2))
Z = np.concatenate((X,Y), axis = 0) # returns a 4 x 2 array
W = np.concatenate((X,Y), axis = 1) # returns a 2 x 4 array
# alternatively
Z2 = np.vstack((X,Y))
W2 = np.hstack((X,Y))