NDArrays

Create an N-dimensional array (ndarray)

import numpy as np myArray = np.array([[1,2,3],[4,5,6]])
  • An N-dimensional array is an array with some number of dimensions (such as a 2D matrix), allowing for more efficient calculations on values.
  • It is useful for data science, machine learning, and other applications.
  • The example above creates a 2x3 matrix (2 rows of 3 columns each).

Alternative initializations

myArray = np.zeros((2,3)) # Init a 2x3 array with all values as 0 myArray = np.random.rand(2,3) # Init a 2x3 array with all values as random numbers from 0 up to 1 myArray = np.random.randn(2,3) # Values are from a standard normal distribution with mean 0 and st-dev of 1

Element-wise operations between ndarrays

np.add(myArray1,myArray2) np.subtract(myArray1,myArray2) np.multiply(myArray1,myArray2) np.divide(myArray1,myArray2)
  • If array 1 and 2 are both the same shape, the resulting array will have the same shape, each element with the sum of the others' values at that element.
  • For example, adding [[1,1],[1,1]] and [[2,2],[2,2]]) will result in [[3,3],[3,3]].

Matrix multipliction

np.matmul(myArray1,myArray2)
  • This kind of multiplication uses the dot product between vectors (rows and columns) of the matrices.
  • For this to work, the first matrix must have a number of columns equal to the number of rows of matrix 2.
  • In some cases you can use ".dot" instead of ".matmul"

Operations on single ndarrays

np.mean(myArray1) # Get the average of the values np.sum(myArray1) # Get total of the values np.sqrt(myArray1) # Get an ndarray with the square root of each value np.exp(myArray1) # Get an ndarray with e^x of each value np.square(myArray1) # Get an ndarray with each value squared (x^2) np.sin(myArray1) # Get an ndarray with the sine of each value myArray1.shape # Get a tuple with the size of each dimension myArray1.flatten() # Convert it to a 1-dimensional array with the values ...
  • In the "sum" and "mean" functions, you can specify which axis to add on (axis=0 makes it add along the vertical axis).
  • Another optional parameter is "keepdims"; set it to True for the resulting ndarray to not get rid of the axis that was reduced, but make its size 1.

Challenge

Create a 2x3 ndarray and a 3x4 ndarray, each with random values. Apply matrix multiplication to those to make array3. Display the shape of the result (it should be (2,4)). Create array4 as a 2x4 array with the following values in the top row (1,2,3,4) and the following values in the second row (5,6,7,8) and do element-wise multiplication between array4 and array3. Take the square root of each element, and then get the sum of all elements.

Completed