<jupyter_start><jupyter_text><NAME> NUMPY OPERATIONS<jupyter_code># Import Numpy Library
import numpy as np
import warnings
warnings.filterwarnings("ignore")
from IPython.display import Image<jupyter_output><empty_output><jupyter_text>Numpy Array Creation<jupyter_code>list1 = [10,20,30,40,50,60]
list1
# Display the type of an object
type(list1)
#Convert list to Numpy Array
arr1 = np.array(list1)
arr1
#Memory address of an array object
arr1.data
# Display type of an object
type(arr1)
#Datatype of array
arr1.dtype
# Convert Integer Array to FLOAT
arr1.astype(float)
# Generate evenly spaced numbers (space =1) between 0 to 10
np.arange(0,10)
# Generate numbers between 0 to 100 with a space of 10
np.arange(0,100,10)
# Generate numbers between 10 to 100 with a space of 10 in descending order
np.arange(100, 10, -10)
#Shape of Array
arr3 = np.arange(0,10)
arr3.shape
arr3
# Size of array
arr3.size
# Dimension 
arr3.ndim
# Datatype of object
arr3.dtype
# Bytes consumed by one element of an array object
arr3.itemsize
# Bytes consumed by an array object
arr3.nbytes
# Length of array
len(arr3)
# Generate an array of zeros
np.zeros(10)
# Generate an array of ones with given shape
np.ones(10)
# Repeat 10 five times in an array
np.repeat(10,5)
# Repeat each element in array 'a' thrice
a= np.array([10,20,30])
np.repeat(a,3)
# Array of 10's
np.full(5,10)
# Generate array of Odd numbers
ar1 = np.arange(1,20)
ar1[ar1%2 ==1]
# Generate array of even numbers
ar1 = np.arange(1,20)
ar1[ar1%2 == 0]
# Generate evenly spaced 4 numbers between 10 to 20.
np.linspace(10,20,4)
# Generate evenly spaced 11 numbers between 10 to 20.
np.linspace(10,20,11)
# Create an array of random values
np.random.random(4)
# Generate an array of Random Integer numbers
np.random.randint(0,500,5)
# Generate an array of Random Integer numbers
np.random.randint(0,500,10)
# Using random.seed we can generate same number of Random numbers
np.random.seed(123)
np.random.randint(0,100,10)
# Using random.seed we can generate same number of Random numbers
np.random.seed(123)
np.random.randint(0,100,10)
# Using random.seed we can generate same number of Random numbers
np.random.seed(101)
np.random.randint(0,100,10)
# Using random.seed we can generate same number of Random numbers
np.random.seed(101)
np.random.randint(0,100,10)
# Generate array of Random float numbers
f1 = np.random.uniform(5,10, size=(10))
f1
# Extract Integer part
np.floor(f1)
# Truncate decimal part
np.trunc(f1)
# Convert Float Array to Integer array
f1.astype(int)
# Normal distribution (mean=0 and variance=1)
b2 =np.random.randn(10)
b2
arr1
# Enumerate for Numpy Arrays
for index, value in np.ndenumerate(arr1):
    print(index, value)<jupyter_output>(0,) 10
(1,) 20
(2,) 30
(3,) 40
(4,) 50
(5,) 60<jupyter_text>Operations on an Array<jupyter_code>arr2 = np.arange(1,20)
arr2
# Sum of all elements in an array
arr2.sum()
# Cumulative Sum
np.cumsum(arr2)
# Find Minimum number in an array
arr2.min()
# Find MAX number in an array
arr2.max()
# Find INDEX of Minimum number in an array
arr2.argmin()
# Find INDEX of MAX number in an array
arr2.argmax()
# Find mean of all numbers in an array
arr2.mean()
# Find median of all numbers present in arr2
np.median(arr2)
# Variance
np.var(arr2)
# Standard deviation
np.std(arr2)
# Calculating percentiles
np.percentile(arr2,70)
# 10th & 70th percentile
np.percentile(arr2,[10,70])<jupyter_output><empty_output><jupyter_text>Operations on a 2D Array<jupyter_code>A = np.array([[1,2,3,0] , [5,6,7,22] , [10 , 11 , 1 ,13] , [14,15,16,3]])
A
# SUM of all numbers in a 2D array
A.sum()
# MAX number in a 2D array
A.max()
# Minimum
A.min()
# Column wise mimimum value 
np.amin(A, axis=0)
# Row wise mimimum value 
np.amin(A, axis=1)
# Mean of all numbers in a 2D array
A.mean()
# Mean
np.mean(A)
# Median
np.median(A)
# 50 percentile = Median
np.percentile(A,50)
np.var(A)
np.std(A)
np.percentile(arr2,70)
# Enumerate for Numpy 2D Arrays
for index, value in np.ndenumerate(A):
    print(index, value)<jupyter_output>(0, 0) 1
(0, 1) 2
(0, 2) 3
(0, 3) 0
(1, 0) 5
(1, 1) 6
(1, 2) 7
(1, 3) 22
(2, 0) 10
(2, 1) 11
(2, 2) 1
(2, 3) 13
(3, 0) 14
(3, 1) 15
(3, 2) 16
(3, 3) 3<jupyter_text>Reading elements of an array<jupyter_code>a = np.array([7,5,3,9,0,2])
# Access first element of the array
a[0]
# Access all elements of Array except first one.
a[1:]
# Fetch 2nd , 3rd & 4th value from the Array
a[1:4]
# Get last element of the array
a[-1]
a[-3]
a[-6]
a[-3:-1]<jupyter_output><empty_output><jupyter_text>Replace elements in array<jupyter_code>ar = np.arange(1,20)
ar
# Replace EVEN numbers with ZERO
rep1 = np.where(ar % 2 == 0, 0 , ar)
print(rep1)
ar2 = np.array([10, 20 , 30 , 10 ,10 ,20, 20])
ar2
# Replace 10 with value 99
rep2 = np.where(ar2 == 10, 99 , ar2)
print(rep2)
p2 = np.arange(0,100,10)
p2
# Replace values at INDEX loc 0,3,5 with 33,55,99
np.put(p2, [0, 3 , 5], [33, 55, 99])
p2<jupyter_output><empty_output><jupyter_text>Missing Values in an array<jupyter_code>a = np.array([10 ,np.nan,20,30,60,np.nan,90,np.inf])
a
# Search for missing values and return as a boolean array
np.isnan(a)
# Index of missing values in an array
np.where(np.isnan(a))
# Replace all missing values with 99
a[np.isnan(a)] = 99
a
# Check if array has any NULL value
np.isnan(a).any()
A = np.array([[1,2,np.nan,4] , [np.nan,6,7,8] , [10 , np.nan , 12 ,13] , [14,15,16,17]])
A
# Search for missing values and return as a boolean array
np.isnan(A)
# Index of missing values in an array
np.where(np.isnan(A))<jupyter_output><empty_output><jupyter_text>Stack Arrays Vertically<jupyter_code>a = np.zeros(20).reshape(2,-1)
b = np.repeat(1, 20).reshape(2,-1)
a
b
np.vstack([a,b])
a1 = np.array([[1], [2], [3]])
b1 = np.array([[4], [5], [6]])
a1
b1
np.vstack([a1,b1])<jupyter_output><empty_output><jupyter_text>Stack Arrays Horizontally<jupyter_code>np.hstack([a,b])
np.hstack([a1,b1])
### hstack & vstack

arr1 = np.array([[7,13,14],[18,10,17],[11,12,19]])
arr2= np.array([16,6,1])
arr3= np.array([[5,8,4,3]])

np.hstack((np.vstack((arr1,arr2)),np.transpose(arr3)))<jupyter_output><empty_output><jupyter_text>Common items between two Arrays<jupyter_code>c1 = np.array([10,20,30,40,50,60])
c2 = np.array([12,20,33,40,55,60])
np.intersect1d(c1,c2)<jupyter_output><empty_output><jupyter_text>Remove Common Elements<jupyter_code># Remove common elements of C1 & C2 array from C1

np.setdiff1d(c1,c2)<jupyter_output><empty_output><jupyter_text>Process Elements on Conditions<jupyter_code>a = np.array([1,2,3,6,8])
b = np.array([10,2,30,60,8])

np.where(a == b) # returns the indices of elements in an input array where the given condition is satisfied.
# Return an array where condition is satisfied
a[np.where(a == b)]
# Return all numbers betweeen 20 & 35
a1 = np.arange(0,60)
a1[np.where ((a1>20) & (a1<35))]
# Return all numbers betweeen 20 & 35 OR numbers divisible by 10
a1 = np.arange(0,60)
a1[np.where (((a1>20) & (a1<35)) | (a1 % 10 ==0)) ]
# Return all numbers betweeen 20 & 35 using np.logical_and
a1[np.where(np.logical_and(a1>20, a1<35))]<jupyter_output><empty_output><jupyter_text>Check for elements in an Array using isin()<jupyter_code>a = np.array([10,20,30,40,50,60,70])
a
# Check whether number 11 & 20 are present in an array
np.isin(a, [11,20])
#Display the matching numbers
a[np.isin(a,20)]
# Check whether number 33 is present in an array
np.isin(a, 33)
a[np.isin(a, 33)]
b = np.array([10,20,30,40,10,10,70,80,70,90])
b
# Check whether number 10 & 70 are present in an array
np.isin(b, [10,70])
# Display the indices where match occurred
np.where(np.isin(b, [10,70]))
# Display the matching values
b[np.where(np.isin(b, [10,70]))]
# Display the matching values
b[np.isin(b, [10,70])]<jupyter_output><empty_output><jupyter_text>Reverse Array<jupyter_code>a4 = np.arange(10,30)
a4
# Reverse the array
a4[::-1]
# Reverse the array
np.flip(a4)
a3 = np.array([[3,2,8,1] , [70,50,10,67] , [45,25,75,15] , [12,9,77,4]])
a3
# Reverse ROW positions
a3[::-1,]
# Reverse COLUMN positions
a3[:,::-1]
# Reverse both ROW & COLUMN positions
a3[::-1,::-1]<jupyter_output><empty_output><jupyter_text>Sorting Array<jupyter_code>a = np.array([10,5,2,22,12,92,17,33])
# Sort array in ascending order
np.sort(a)
a3 = np.array([[3,2,8,1] , [70,50,10,67] , [45,25,75,15]])
a3
# Sort along rows
np.sort(a3)
# Sort along rows
np.sort(a3,axis =1)
# Sort along columns
np.sort(a3,axis =0)
# Sort in descending order
b = np.sort(a)
b = b[::-1]
b
# Sort in descending order
c = np.sort(a)
np.flip(c)
# Sort in descending order
a[::-1].sort()
a<jupyter_output><empty_output><jupyter_text>"N" Largest & Smallest Numbers in an Array<jupyter_code>p = np.arange(0,50)
p
np.random.shuffle(p)
p
# Return "n" largest numbers in an Array
n = 4
p[np.argsort(p)[-nth:]]
# Return "n" largest numbers in an Array
p[np.argpartition(-p,n)[:n]]
# Return "n" smallest numbers in an Array
p[np.argsort(-p)[-n:]]
# Return "n" smallest numbers in an Array
p[np.argpartition(p,n)[:n]]<jupyter_output><empty_output><jupyter_text>Repeating Sequences<jupyter_code>a5 = [10,20,30] 
a5
# Repeat whole array twice
np.tile(a5, 2)
# Repeat each element in an array thrice
np.repeat(a5, 3)<jupyter_output><empty_output><jupyter_text>Compare Arrays<jupyter_code>d1 = np.arange(0,10)
d1
d2 = np.arange(0,10)
d2
d3 = np.arange(10,20)
d3
d4 = d1[::-1]
d4
# Compare arrays using "allclose" function. If this function returns True then Arrays are equal
res1 = np.allclose(d1,d2)
res1
# Compare arrays using "allclose" function. If this function returns False then Arrays are not equal
res2 = np.allclose(d1,d3)
res2
# Compare arrays using "allclose" function.
res3 = np.allclose(d1,d4)
res3<jupyter_output><empty_output><jupyter_text>Frequent Values in an Array<jupyter_code># unique numbers in an array
b = np.array([10,10,10,20,30,20,30,30,20,10,10,30,10])
np.unique(b)
# unique numbers in an array along with the count E.g value 10 occurred maximum times (5 times) in an array "b"
val , count = np.unique(b,return_counts=True)
val,count
# 10 is the most frequent value 
np.bincount(b).argmax()<jupyter_output><empty_output><jupyter_text>Read-Only Array<jupyter_code>d5 = np.arange(10,100,10)
d5
# Make arrays immutable  
d5.flags.writeable = False
d5[0] = 99
d5[2] = 11<jupyter_output><empty_output><jupyter_text>Load & Save<jupyter_code># Load data from a text file using loadtext
p4 = np.loadtxt('sample.txt', 
                dtype = np.integer # Decides the datatype of resulting array
               )
p4
# Load data from a text file using genfromtxt
p5 = np.genfromtxt('sample0.txt',dtype='str')
p5
# Accessing specific rows
p5[0]
# Accessing specific columns
p5[:,0]
p6 = np.genfromtxt('sample2.txt', 
                   delimiter=' ', 
                   dtype=None, 
                   names=('Name', 'ID', 'Age')
                  )
p6
# Skip header using "skiprows" parameter
p6 = np.loadtxt('sample2.txt', 
                   delimiter=' ', 
                   dtype=[('Name', str, 50), ('ID', np.integer), ('Age', np.integer)], 
                   skiprows=1
                  )
p6
# Return only first & third column using "usecols" parameter
np.loadtxt('sample.txt', delimiter =' ', usecols =(0, 2)) 
# Return only three rows using "max_rows" parameter
p6 = np.loadtxt('sample2.txt', 
                   delimiter=' ', 
                   dtype=[('Name', str, 50), ('ID', np.integer), ('Age', np.integer)], 
                   skiprows=1,
                   max_rows = 3
                  )
p6
# Skip header using "skip_header" parameter
p6 = np.genfromtxt('sample2.txt', 
                   delimiter=' ', 
                   dtype=[('Name', str, 50), ('ID', np.integer), ('Age', np.float)], 
                   names=('Name', 'ID', 'Age'),
                   skip_header=1
                  )
p6
p7 = np.arange(10,200,11)
p7
np.savetxt('test3.csv', p7, delimiter=',')
p8 = np.arange(0,121).reshape(11,11)
p8
np.save('test4.npy', p8)
p9 = np.load('test4.npy')
p9
np.save('numpyfile', p8)
p10 = np.load('numpyfile.npy')
p10
p11 = np.arange(0,1000000).reshape(1000,1000)
p11
# Save Numpy array to a compressed file
np.savez_compressed('test6.npz', p11)
# Save Numpy array to a npy file
np.save('test7.npy', p11)
# Compressed file size is much lesser than normal npy file
Image(filename='load_save.PNG')<jupyter_output><empty_output><jupyter_text>Printing Options<jupyter_code># Display values upto 4 decimal place
np.set_printoptions(precision=4)
a = np.array([12.654398765 , 90.7864098354674])
a
# Display values upto 2 decimal place
np.set_printoptions(precision=2)
a = np.array([12.654398765 , 90.7864098354674])
a
# Array Summarization
np.set_printoptions(threshold=3)
np.arange(200)
# Reset Formatter
np.set_printoptions(precision=8,suppress=False, threshold=1000, formatter=None)
a = np.array([12.654398765 , 90.7864098354674])
a
np.arange(1,1100)
# Display all values
np.set_printoptions(threshold=np.inf)
np.arange(1,1100)<jupyter_output><empty_output><jupyter_text>Vector Addition<jupyter_code>v1 = np.array([1,2])
v2 = np.array([3,4])
v3 = v1+v2
v3 = np.add(v1,v2)
print('V3 =' ,v3)<jupyter_output>V3 = [4 6]<jupyter_text>Multiplication of vectors<jupyter_code>a1 = [5 , 6 ,8]
a2 = [4, 7 , 9]
print(np.multiply(a1,a2))<jupyter_output>[20 42 72]<jupyter_text>Dot Product<jupyter_code>a1 = np.array([1,2,3])
a2 = np.array([4,5,6])

dotp = a1@a2
print(" Dot product - ",dotp)

dotp = np.dot(a1,a2)
print(" Dot product usign np.dot",dotp)

dotp = np.inner(a1,a2)
print(" Dot product usign np.inner", dotp)

dotp = sum(np.multiply(a1,a2))
print(" Dot product usign np.multiply & sum",dotp)

dotp = np.matmul(a1,a2)
print(" Dot product usign np.matmul",dotp)

dotp = 0
for i in range(len(a1)):
    dotp = dotp + a1[i]*a2[i]
print(" Dot product usign for loop" , dotp)<jupyter_output>Dot product -  32
 Dot product usign np.dot 32
 Dot product usign np.inner 32
 Dot product usign np.multiply & sum 32
 Dot product usign np.matmul 32
 Dot product usign for loop 32<jupyter_text>Length of Vector<jupyter_code>v3 = np.array([1,2,3,4,5,6])
length = np.sqrt(np.dot(v3,v3))
length
v3 = np.array([1,2,3,4,5,6])
length = np.sqrt(sum(np.multiply(v3,v3)))
length
v3 = np.array([1,2,3,4,5,6])
length = np.sqrt(np.matmul(v3,v3))
length<jupyter_output><empty_output><jupyter_text>Normalized Vector<jupyter_code>#First Method
v1 = [2,3]
length_v1 = np.sqrt(np.dot(v1,v1))
norm_v1 = v1/length_v1
length_v1 , norm_v1
#Second Method
v1 = [2,3]
norm_v1 = v1/np.linalg.norm(v1)
norm_v1<jupyter_output><empty_output><jupyter_text>Angle between vectors<jupyter_code>#First Method
v1 = np.array([8,4])
v2 = np.array([-4,8])
ang = np.rad2deg(np.arccos( np.dot(v1,v2) / (np.linalg.norm(v1)*np.linalg.norm(v2))))
ang
#Second Method
v1 = np.array([4,3])
v2 = np.array([-3,4])
lengthV1 = np.sqrt(np.dot(v1,v1)) 
lengthV2  = np.sqrt(np.dot(v2,v2))
ang = np.rad2deg(np.arccos( np.dot(v1,v2) / (lengthV1 * lengthV2)))
print('Angle between Vectors - %s' %ang)<jupyter_output>Angle between Vectors - 90.0<jupyter_text>Inner & outer products<jupyter_code>v1 = np.array([1,2,3])
v2 = np.array([4,5,6])
np.inner(v1,v2)

print("\n Inner Product ==>  \n", np.inner(v1,v2))
print("\n Outer Product ==>  \n", np.outer(v1,v2))<jupyter_output>Inner Product ==>  
 32

 Outer Product ==>  
 [[ 4  5  6]
 [ 8 10 12]
 [12 15 18]]<jupyter_text>Vector Cross Product<jupyter_code>v1 = np.array([1,2,3])
v2 = np.array([4,5,6])
print("\nVector Cross Product ==>  \n", np.cross(v1,v2))<jupyter_output>Vector Cross Product ==>  
 [-3  6 -3]<jupyter_text>Matrix Creation<jupyter_code># Create a 4x4 matrix
A = np.array([[1,2,3,4] , [5,6,7,8] , [10 , 11 , 12 ,13] , [14,15,16,17]])
A
# Datatype of Matrix
A.dtype
B = np.array([[1.5,2.07,3,4] , [5,6,7,8] , [10 , 11 , 12 ,13] , [14,15,16,17]])
B
# Datatype of Matrix
B.dtype
# Shape of Matrix
A.shape
# Generate a 4x4 zero matrix
np.zeros((4,4))
#Shape of Matrix
z1 = np.zeros((4,4))
z1.shape
# Generate a 5x5 matrix filled with ones
np.ones((5,5))
# Return 10x10 matrix of random integer numbers between 0 to 500
np.random.randint(0,500, (10,10))
arr2
arr2.reshape(5,4)
mat1 = np.random.randint(0,1000,100).reshape(10,10)
mat1
mat1[0,0]
mat1[mat1 > 500]
# Identity Matrix : https://en.wikipedia.org/wiki/Identity_matrix

I = np.eye(9)
I
# Diagonal Matrix : https://en.wikipedia.org/wiki/Diagonal_matrix

D = np.diag([1,2,3,4,5,6,7,8])
D
# Traingular Matrices (lower & Upper triangular matrix) : https://en.wikipedia.org/wiki/Triangular_matrix

M = np.random.randn(5,5)
U = np.triu(M)
L = np.tril(M)
print("lower triangular matrix - \n" , M)
print("\n")


print("lower triangular matrix - \n" , L)
print("\n")

print("Upper triangular matrix - \n" , U)

# Generate a 5X5 matrix with a given fill value of 8
np.full((5,5) , 8)
# Generate 5X5 matrix of Random float numbers between 10 to 20
np.random.uniform(10,20, size=(5,5))
A
# Collapse Matrix into one dimension array
A.flatten()
# Collapse Matrix into one dimension array
A.ravel()<jupyter_output><empty_output><jupyter_text>Reading elements of a Matrix<jupyter_code>A
# Fetch first row of matrix
A[0,]
# Fetch first column of matrix
A[:,0]
# Fetch first element of the matrix
A[0,0]
A[1:3 , 1:3]<jupyter_output><empty_output><jupyter_text>Reverse Rows / Columns of a Matrix<jupyter_code>arr = np.arange(16).reshape(4,4)
arr
# Reverse rows
arr[::-1]
#Reverse Columns
arr[:, ::-1]<jupyter_output><empty_output><jupyter_text>SWAP Rows & Columns<jupyter_code>m1 = np.arange(0,16).reshape(4,4)
m1
# SWAP rows 0 & 1
m1[[0,1]] = m1[[1,0]]
m1
# SWAP rows 2 & 3
m1[[3,2]] = m1[[2,3]]
m1
m2 = np.arange(0,36).reshape(6,6)
m2
# Swap columns 0 & 1
m2[:,[0, 1]] = m2[:,[1, 0]]
m2
# Swap columns 2 & 3
m2[:,[2, 3]] = m2[:,[3, 2]]
m2<jupyter_output><empty_output><jupyter_text>Concatenate Matrices Matrix Concatenation : https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html<jupyter_code>A = np.array([[1,2] , [3,4] ,[5,6]])
B = np.array([[1,1] , [1,1]])
C = np.concatenate((A,B))
C<jupyter_output><empty_output><jupyter_text>Matrix Addition<jupyter_code>#********************************************************#
M = np.array([[1,2,3],[4,-3,6],[7,8,0]])
N = np.array([[1,1,1],[2,2,2],[3,3,3]])

print("\n First Matrix (M)  ==>  \n", M)
print("\n Second Matrix (N)  ==>  \n", N)

C = M+N
print("\n Matrix Addition (M+N)  ==>  \n", C)

# OR

C = np.add(M,N,dtype = np.float64)
print("\n Matrix Addition using np.add  ==>  \n", C)

#********************************************************#<jupyter_output>First Matrix (M)  ==>  
 [[ 1  2  3]
 [ 4 -3  6]
 [ 7  8  0]]

 Second Matrix (N)  ==>  
 [[1 1 1]
 [2 2 2]
 [3 3 3]]

 Matrix Addition (M+N)  ==>  
 [[ 2  3  4]
 [ 6 -1  8]
 [10 11  3]]

 Matrix Addition using np.add  ==>  
 [[ 2.  3.  4.]
 [ 6. -1.  8.]
 [10. 11.  3.]]<jupyter_text>Matrix subtraction<jupyter_code>#********************************************************#
M = np.array([[1,2,3],[4,-3,6],[7,8,0]])
N = np.array([[1,1,1],[2,2,2],[3,3,3]])

print("\n First Matrix (M)  ==>  \n", M)
print("\n Second Matrix (N)  ==>  \n", N)

C = M-N
print("\n Matrix Subtraction (M-N)  ==>  \n", C)

# OR

C = np.subtract(M,N,dtype = np.float64)
print("\n Matrix Subtraction using np.subtract  ==>  \n", C)

#********************************************************#<jupyter_output>First Matrix (M)  ==>  
 [[ 1  2  3]
 [ 4 -3  6]
 [ 7  8  0]]

 Second Matrix (N)  ==>  
 [[1 1 1]
 [2 2 2]
 [3 3 3]]

 Matrix Subtraction (M-N)  ==>  
 [[ 0  1  2]
 [ 2 -5  4]
 [ 4  5 -3]]

 Matrix Subtraction using np.subtract  ==>  
 [[ 0.  1.  2.]
 [ 2. -5.  4.]
 [ 4.  5. -3.]]<jupyter_text>Matrices Scalar Multiplication<jupyter_code>M = np.array([[1,2,3],[4,-3,6],[7,8,0]])

C = 10

print("\n Matrix (M)  ==>  \n", M)

print("\nMatrices Scalar Multiplication ==>  \n", C*M)

# OR

print("\nMatrices Scalar Multiplication ==>  \n", np.multiply(C,M))<jupyter_output>Matrix (M)  ==>  
 [[ 1  2  3]
 [ 4 -3  6]
 [ 7  8  0]]

Matrices Scalar Multiplication ==>  
 [[ 10  20  30]
 [ 40 -30  60]
 [ 70  80   0]]

Matrices Scalar Multiplication ==>  
 [[ 10  20  30]
 [ 40 -30  60]
 [ 70  80   0]]<jupyter_text>Transpose of a matrix<jupyter_code>M = np.array([[1,2,3],[4,-3,6],[7,8,0]])

print("\n Matrix (M)  ==>  \n", M)

print("\nTranspose of M ==>  \n", np.transpose(M))

# OR

print("\nTranspose of M ==>  \n", M.T)<jupyter_output>Matrix (M)  ==>  
 [[ 1  2  3]
 [ 4 -3  6]
 [ 7  8  0]]

Transpose of M ==>  
 [[ 1  4  7]
 [ 2 -3  8]
 [ 3  6  0]]

Transpose of M ==>  
 [[ 1  4  7]
 [ 2 -3  8]
 [ 3  6  0]]<jupyter_text>Determinant of a matrix<jupyter_code>M = np.array([[1,2,3],[4,-3,6],[7,8,0]])

print("\n Matrix (M)  ==>  \n", M)

print("\nDeterminant of M ==>  ", np.linalg.det(M))<jupyter_output>Matrix (M)  ==>  
 [[ 1  2  3]
 [ 4 -3  6]
 [ 7  8  0]]

Determinant of M ==>   195.0<jupyter_text>Rank of a matrix<jupyter_code>M = np.array([[1,2,3],[4,-3,6],[7,8,0]])

print("\n Matrix (M)  ==>  \n", M)

print("\nRank of M ==> ", np.linalg.matrix_rank(M))<jupyter_output>Matrix (M)  ==>  
 [[ 1  2  3]
 [ 4 -3  6]
 [ 7  8  0]]

Rank of M ==>  3<jupyter_text>Trace of matrix<jupyter_code>M = np.array([[1,2,3],[4,-3,6],[7,8,0]])

print("\n Matrix (M)  ==>  \n", M)

print("\nTrace of M ==> ", np.trace(M))<jupyter_output>Matrix (M)  ==>  
 [[ 1  2  3]
 [ 4 -3  6]
 [ 7  8  0]]

Trace of M ==>  -2<jupyter_text>Inverse of matrix A<jupyter_code>M = np.array([[1,2,3],[4,-3,6],[7,8,0]])

print("\n Matrix (M)  ==>  \n", M)

print("\nInverse of M ==> \n", np.linalg.inv(M))<jupyter_output>Matrix (M)  ==>  
 [[ 1  2  3]
 [ 4 -3  6]
 [ 7  8  0]]

Inverse of M ==> 
 [[-0.24615385  0.12307692  0.10769231]
 [ 0.21538462 -0.10769231  0.03076923]
 [ 0.27179487  0.03076923 -0.05641026]]<jupyter_text>Matrix Multiplication (pointwise multiplication)<jupyter_code>M = np.array([[1,2,3],[4,-3,6],[7,8,0]])
N = np.array([[1,1,1],[2,2,2],[3,3,3]])

print("\n First Matrix (M)  ==>  \n", M)
print("\n Second Matrix (N)  ==>  \n", N)

print("\n Point-Wise Multiplication of M & N  ==> \n", M*N)

# OR

print("\n Point-Wise Multiplication of M & N  ==> \n", np.multiply(M,N))<jupyter_output>First Matrix (M)  ==>  
 [[ 1  2  3]
 [ 4 -3  6]
 [ 7  8  0]]

 Second Matrix (N)  ==>  
 [[1 1 1]
 [2 2 2]
 [3 3 3]]

 Point-Wise Multiplication of M & N  ==> 
 [[ 1  2  3]
 [ 8 -6 12]
 [21 24  0]]

 Point-Wise Multiplication of M & N  ==> 
 [[ 1  2  3]
 [ 8 -6 12]
 [21 24  0]]<jupyter_text>Matrix dot product<jupyter_code>M = np.array([[1,2,3],[4,-3,6],[7,8,0]])
N = np.array([[1,1,1],[2,2,2],[3,3,3]])

print("\n First Matrix (M)  ==>  \n", M)
print("\n Second Matrix (N)  ==>  \n", N)

print("\n Matrix Dot Product ==> \n", M@N)

# OR

print("\n Matrix Dot Product using np.matmul ==> \n", np.matmul(M,N))

# OR

print("\n Matrix Dot Product using np.dot ==> \n", np.dot(M,N))<jupyter_output>First Matrix (M)  ==>  
 [[ 1  2  3]
 [ 4 -3  6]
 [ 7  8  0]]

 Second Matrix (N)  ==>  
 [[1 1 1]
 [2 2 2]
 [3 3 3]]

 Matrix Dot Product ==> 
 [[14 14 14]
 [16 16 16]
 [23 23 23]]

 Matrix Dot Product using np.matmul ==> 
 [[14 14 14]
 [16 16 16]
 [23 23 23]]

 Matrix Dot Product using np.dot ==> 
 [[14 14 14]
 [16 16 16]
 [23 23 23]]<jupyter_text>Matrix Division<jupyter_code>M = np.array([[1,2,3],[4,-3,6],[7,8,0]])
N = np.array([[1,1,1],[2,2,2],[3,3,3]])

print("\n First Matrix (M)  ==>  \n", M)
print("\n Second Matrix (N)  ==>  \n", N)


print("\n Matrix Division (M/N)   ==> \n", M/N)

# OR

print("\n Matrix Division (M/N)   ==> \n", np.divide(M,N))<jupyter_output>First Matrix (M)  ==>  
 [[ 1  2  3]
 [ 4 -3  6]
 [ 7  8  0]]

 Second Matrix (N)  ==>  
 [[1 1 1]
 [2 2 2]
 [3 3 3]]

 Matrix Division (M/N)   ==> 
 [[ 1.          2.          3.        ]
 [ 2.         -1.5         3.        ]
 [ 2.33333333  2.66666667  0.        ]]

 Matrix Division (M/N)   ==> 
 [[ 1.          2.          3.        ]
 [ 2.         -1.5         3.        ]
 [ 2.33333333  2.66666667  0.        ]]<jupyter_text>Sum of all elements in a matrix<jupyter_code>N = np.array([[1,1,1],[2,2,2],[3,3,3]])

print("\n Matrix (N)  ==>  \n", N)


print ("Sum of all elements in a Matrix  ==>")
print (np.sum(N))<jupyter_output>Matrix (N)  ==>  
 [[1 1 1]
 [2 2 2]
 [3 3 3]]
Sum of all elements in a Matrix  ==>
18<jupyter_text>Column-Wise Addition<jupyter_code>N = np.array([[1,1,1],[2,2,2],[3,3,3]])

print("\n Matrix (N)  ==>  \n", N)

print ("Column-Wise summation ==> ")
print (np.sum(N,axis=0))<jupyter_output>Matrix (N)  ==>  
 [[1 1 1]
 [2 2 2]
 [3 3 3]]
Column-Wise summation ==> 
[6 6 6]<jupyter_text>Row-Wise Addition<jupyter_code>N = np.array([[1,1,1],[2,2,2],[3,3,3]])

print("\n Matrix (N)  ==>  \n", N)

print ("Row-Wise summation  ==>")
print (np.sum(N,axis=1))<jupyter_output>Matrix (N)  ==>  
 [[1 1 1]
 [2 2 2]
 [3 3 3]]
Row-Wise summation  ==>
[3 6 9]<jupyter_text>Kronecker Product of matrices<jupyter_code>M1 = np.array([[1,2,3] , [4,5,6]]) 
M1
M2 = np.array([[10,10,10],[10,10,10]])
M2
np.kron(M1,M2)<jupyter_output><empty_output><jupyter_text>Matrix Powers<jupyter_code>M1 = np.array([[1,2],[4,5]])
M1
#Matrix to the power 3

M1@M1@M1
#Matrix to the power 3

np.linalg.matrix_power(M1,3)<jupyter_output><empty_output><jupyter_text>Tensor<jupyter_code># Create Tensor

T1 = np.array([
  [[1,2,3],    [4,5,6],    [7,8,9]],
  [[10,20,30], [40,50,60], [70,80,90]],
  [[100,200,300], [400,500,600], [700,800,900]],
  ])

T1
T2 = np.array([
  [[0,0,0] , [0,0,0] , [0,0,0]],
  [[1,1,1] , [1,1,1] , [1,1,1]],
  [[2,2,2] , [2,2,2] , [2,2,2]]
    
])

T2<jupyter_output><empty_output><jupyter_text>Tensor Addition<jupyter_code>A = T1+T2
A
np.add(T1,T2)<jupyter_output><empty_output><jupyter_text>Tensor Subtraction<jupyter_code>S = T1-T2
S
np.subtract(T1,T2)<jupyter_output><empty_output><jupyter_text>Tensor Element-Wise Product<jupyter_code>P = T1*T2
P
np.multiply(T1,T2)<jupyter_output><empty_output><jupyter_text>Tensor Element-Wise Division<jupyter_code>D = T1/T2
D
np.divide(T1,T2)<jupyter_output>C:\Anaconda\lib\site-packages\ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in true_divide
  """Entry point for launching an IPython kernel.<jupyter_text>Tensor Dot Product<jupyter_code>T1
T2
np.tensordot(T1,T2)<jupyter_output><empty_output><jupyter_text>Solving Equations $$AX = B$$<jupyter_code>A = np.array([[1,2,3] , [4,5,6] , [7,8,9]])
A
B = np.random.random((3,1))
B
# Ist Method
X = np.dot(np.linalg.inv(A) , B)
X
# 2nd Method
X = np.matmul(np.linalg.inv(A) , B)
X
# 3rd Method
X = np.linalg.inv(A)@B
X
# 4th Method
X = np.linalg.solve(A,B)
X<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.18864489703037887, 'fraction_numerical': 0.08571320210869647, 'mean_word_length': 4.203868166567989, 'pattern_counts': {'":': 0, '<': 214, '<?xml version=': 0, '>': 303, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 4, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '58', 'dir': 'jupyter-structured-clean-dedup', 'id': '45339', 'license': 'MIT', 'n_tokens_mistral': 12399, 'n_tokens_neox': 11386, 'n_words': 2713, 'path': 'Machine Learning/Libraries/Introduction_to_numpy.ipynb', 'repo_name': 'theshredbox/DS-ScriptsNook', 'size': '26380'}