This is a fundamental Package for scientific computing for manipulation of multi-dimensional arrays and matrices. It is particularly useful for linear algebra, Fourier transform, random number simulation etc
Matrices are rectangular array of numbers, symbols and expressions arranged in rows and columns. The numbers, symbols or expressions in the matrix are called its entries or its elements. The horizontal and vertical lines of entries in a matrix are called rows and columns, respectively. Its operations inclue addition, subtraction, multiplication
The first step is to import numpy library into the active notebook
import numpy
To shorten the length of any library, a better alternative is to instantiate the library with a shorter name, as in
import numpy as np
With this, each time numpy is required on this active notebook, np will be used instead
The np.array function is used to create an array
#creating a 1 dimensional array
x = np.array([1, 2, 3, 4, 5])
y = np.array((9, 10))
print(x)
print('The shape of X is', x.shape)
print(y)
print('The shape of Y is', y.shape)
The shape property is usually used to get the current shape of an array
Create a 1 dimensional array
# Creating a 2D arrays
z = np.array([[1, 2], [3, 4], [5, 6]])
print(z)
print('The shape of Z is', z.shape)
Create a 2D array
C = [[3,4], [8,9], [10, 19]]
Numpy has built-in functions for creating arrays and manipulating. These includes:
np.arange
np.reshape
np.zeros
The dimensions (no of rows and column) are passed as parameters to the function.
#arange is Used to create arrays with values in a specified range.
A = np.arange(25)
print(A)
print(A.shape)
C = A.reshape(5,5)
print(C)
#To change the shape of an array
B = A.reshape(25,1)
print (B)
print ("The shape of 1D array X = ", B.shape)
C = B.reshape(5,5)
print ( C)
print ("The shape of array C = ", C.shape)
Note: Before a reshape function will run sucessful, the multiplication of the two parameter supply to the function must be equal with multiplication of the shape of the orginal array you want to reshape.
For example: The shape of variable B is (25, 1) therefore 25 * 1 = 25
The two parameter supply to the reshape function is (5, 5), 5 * 5 = 25
#zeros is used to create an array filled with zeros.
np_Zeros = np.zeros((2,3))
np_Zeros
To access an element in a two-dimensional array, you need to specify an index for both the row and the column.
D = np.array([[5, 7, 8],[3, 5, 9]])
D
# note that for array numbering in numpy, it that from zero
#Row 1, column 0 gives a scalar value
D[1,0]
#Row 1, column 1
D[1,1]
#Row 1, column 2
D[1,2]
# Slicing is also possible in numpy
D[0:1, :]
x = np.array([[1,2,3],[4,5,6]])
y = np.array([[2,2,2],[3,3,3]])
z = np.array([1,2,3])
#Transpose a matrix
x.T
#Elementwise addittion
print (x+y)
print (np.add(x,y))
#Elementwise Subtraction
print (x-y)
print (np.subtract(x,y))
#Elementwise Multiplication
print (x*z)
print (np.multiply(x,z))
# Inner product of vectors
print(np.dot(x, z))