NUMPY
what is NumPy?
numpy----->Numerical Python
fundatmental library for Python
provides muti dimentional array objects
handling the large datasets making a critical tool that require heavy computing
1. Creating NumPy Arrays
1. Using [Link]: Use [Link]() when you want to convert Python lists into NumPy arrays.
import numpy as np
a1 = [Link]([1, 2, 3])
a2 = [Link]([[1, 2], [3, 4]])
a3 = [Link]([[[1, 2], [3, 4]],[[5, 6], [7, 8]]])
print(a1)
print(a2)
print(a3)
output
[1 2 3]
[[1 2]
[3 4]]
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
2. Using Numpy Functions: NumPy provides quick utility functions for creating arrays filled with
zeros, ones, or ranges:
a0 = [Link]((3, 3))
a1 = [Link]((2, 2))
ar = [Link](0, 10, 2)
print(a0)
print(a1)
print(ar)
Output
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[1. 1.]
[1. 1.]]
[0 2 4 6 8]
[Link] Array with Equal Spacing
[Link](0, 1, 5)
Output:
[0. 0.25 0.5 0.75 1. ]
4. Identity Matrix
[Link](3)
Output:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
5. Array with Same Value
[Link]((2, 2), 7)
Output:
[[7 7]
[7 7]]
[Link] Arrays
[Link](3) # random values (0 to 1)
[Link](1, 10, 5) # random integers
Output:
[0.26909495 0.04231653 0.1888104 ]
[8 1 3 7 9]
[Link] array (1 → 20) and reshape to (4,5)
import numpy as np
arr = [Link](1, 21).reshape(4, 5)
print(arr)
Output:
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]]
8. Find shape of random (3×3) array
arr = [Link](3, 3)
print([Link])
Output:
(3, 3)
9. Random array → find max & min
arr = [Link](3, 3)
print("Array:\n", arr)
print("Max:", [Link]())
print("Min:", [Link]())
Example Output:
Array:
[[0.23 0.78 0.11]
[0.56 0.91 0.34]
[0.67 0.45 0.29]]
Max: 0.91
Min: 0.11
[Link] a 3×3 random array Replace all values > 0.5 with 1 Replace all values ≤ 0.5 with 0
import numpy as np
# Step 1: Create 3×3 random array
arr = [Link](3, 3)
# Step 2 & 3: Apply condition
arr[arr > 0.5] = 1
arr[arr <= 0.5] = 0
print(arr)
Example Output
Before:
[[0.2 0.8 0.6]
[0.1 0.4 0.9]
[0.55 0.3 0.7]]
After:
[[0 1 1]
[0 0 1]
[1 0 1]]
2. Indexing & Slicing
1D Indexing
Rule:
[start : end]
start included
end excluded
arr = [Link]([10,20,30,40])
print(arr[0]) # 10
print(arr[-1]) # 40 (last element)
2D Indexing (Matrix Access)
Format:
[row_index, column_index]
2D Slicing
Get full row
print(arr[0]) # [1 2 3]
Get full column
print(arr[:,1]) # [2 5]
Submatrix extraction
print(arr[:, 1:3])
Output:
[[2 3]
[5 6]]
Boolean Indexing (Very Important)
arr = [Link]([10,20,30,40])
print(arr[arr > 25])
Output:
[30 40]
Modify Using Indexing
arr = [Link]([1,2,3,4])
arr[0] = 100
print(arr)
Output:
[100 2 3 4]
3. Core Array Attributes
Example
import numpy as np
arr = [Link]([[10,20,30],[40,50,60]])
[Link] → Dimensions
print([Link])
✔ Output:
(2, 3)
2. ndim → Number of Dimensions
print([Link])
✔ Output:
2
[Link] → Total Elements
print([Link])
✔ Output:
6
4. dtype → Data Type
print([Link])
✔ Output:
int64
All elements are integers
5. [Link] → Memory per Element
print([Link])
✔ Output:
8
Meaning:
Each element takes 8 bytes
6. [Link] → Total Memory Used
print([Link])
✔ Output:
48
Calculation:
6 elements × 8 bytes = 48 bytes
7. arr.T → Transpose
print(arr.T)
✔ Output:
[[10 40]
[20 50]
[30 60]]
Rows ↔ Columns swapped
8. [Link]() → Change Shape
print([Link](3,2))
✔ Output:
[[10 20]
[30 40]
[50 60]]
Same data, different structure
4. What are Vectorized Operations?
Vectorization means:
Performing operations on entire arrays without using Python loops
Basic Vectorized Operations
Example:
import numpy as np
arr = [Link]([1, 2, 3, 4])
print(arr + 5) # [6 7 8 9]
print(arr * 2) # [2 4 6 8]
print(arr ** 2) # [1 4 9 16]
Array-to-Array Operations
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
print(a + b) # [5 7 9]
print(a * b) # [4 10 18]
Comparison (Boolean Vectorization)
arr = [Link]([10, 20, 30, 40])
print(arr > 25) # [False False True True]
print(arr[arr > 25]) # [30 40]
This is heavily used in:
Data filtering
Data cleaning
Conditional Operations (Very Important)
Syntax:
[Link](condition, value_if_true, value_if_false)
Using [Link]()
arr = [Link]([5, 15, 25, 35])
result = [Link](arr > 20, 1, 0)
print(result) # [0 0 1 1]
2D Example:
arr = [Link]([[1,2,3],
[4,5,6]])
print(arr + [Link]([10,20,30]))
Output:
[[11 22 33]
[14 25 36]]
5. Reshaping
What is Reshaping?
changing the dimensions (shape) of an array without changing its data
Total number of elements must remain the same.
Syntax:
[Link](rows, cols)
Rule (Very Important):
Total elements must match
Original → 6 elements
New shape → 2 × 3 = 6
[Link](4,2) # Error (8 ≠ 6)
Using -1 (Automatic Dimension)
NumPy can infer one dimension automatically.
arr = [Link]([1,2,3,4,5,6])
print([Link](2, -1)) # 2 rows, auto columns
print([Link](-1, 3)) # auto rows, 3 columns
Output:
[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]
Flattening (2D → 1D)
Methods:
flatten() → returns copy
ravel() → returns view (faster)
arr = [Link]([[1,2,3],
[4,5,6]])
print([Link]()) # [1 2 3 4 5 6]
Reshape Multi-Dimensional Arrays
arr = [Link](12)
print([Link](3,4)) #2D array
print([Link](2,2,3)) # 3D array
6. Broadcasting
What is Broadcasting?
Broadcasting allows NumPy to perform operations on arrays of different shapes by automatically
expanding the smaller array.
Broadcasting Rules (Must Know)
Two shapes are compatible if:
1. They are equal, OR
2. One of them is 1
Comparison happens from right to left (last dimension first)
Scalar Broadcasting
import numpy as np
arr = [Link]([1,2,3])
print(arr + 10)
Output:
[11 12 13]
1D + 2D Broadcasting
arr = [Link]([[1,2,3],
[4,5,6]])
b = [Link]([10,20,30])
print(arr + b)
Output:
[[11 22 33]
[14 25 36]]
Column Broadcasting
arr = [Link]([[1,2,3],
[4,5,6]])
b = [Link]([[10],
[20]])
print(arr + b)
Output:
[[11 12 13]
[24 25 26]]
Broadcasting Error
a = [Link]([1,2,3])
b = [Link]([1,2])
print(a + b) # ERROR
7. Stacking (Combining Arrays)
Types of Stacking
Horizontal Stacking (hstack)
a = [Link]([1,2,3])
b = [Link]([4,5,6])
print([Link]((a,b)))
Output:
[1 2 3 4 5 6]
🔸 Vertical Stacking (vstack)
print([Link]((a,b)))
Output:
[[1 2 3]
[4 5 6]]
🔸 Column Stacking
print(np.column_stack((a,b)))
Output:
[[1 4]
[2 5]
[3 6]]
🔸 General Stack ([Link])
print([Link]((a,b), axis=0))
Output:
[[1 2 3]
[4 5 6]]
8. Splitting (Breaking Arrays)
Important Rules
Splitting requires equal division
Otherwise → use np.array_split()
Syntax:
np.array_split(given array name, no of equal division)
Horizontal Split
arr = [Link]([1,2,3,4,5,6])
print([Link](arr, 3))
Output:
[array([1,2]), array([3,4]), array([5,6])]
Vertical Split
arr = [Link]([[1,2],
[3,4],
[5,6]])
print([Link](arr, 3))
Output:
[array([[1, 2]]), array([[3, 4]]), array([[5, 6]])]
9. Random Module
What is NumPy Random Module?
The [Link] module generates pseudo-random numbers efficiently for arrays.
Basic Random Functions
[Link]() → Uniform [0, 1)
import numpy as np
print([Link]()) # single value
print([Link](2,3)) # 2x3 matrix
Normal Distribution (mean=0, std=1)
print([Link](3,3))
Random Integers
print([Link](1, 10)) # single value
print([Link](1, 10, (2,3))) # 2x3 array
Range: [low, high)
Setting Seed (VERY IMPORTANT)
[Link](42)
print([Link](3))
Shuffling Data
arr = [Link]([1,2,3,4,5])
[Link](arr)
print(arr)
10. Linear Algebra
1. Dot Product ([Link])
Concept
For vectors → sum of element-wise products.
n
a ⋅b=∑ ai b i
i=1
Example:
import numpy as np
a = [Link]([1,2,3])
b = [Link]([4,5,6])
print([Link](a, b)) # 32
Calculation: 1 ×4 +2 ×5+3 ×6=32
Matrix Multiplication (2D)
A = [Link]([[1,2],
[3,4]])
B = [Link]([[5,6],
[7,8]])
print([Link](A, B))
# or
print(A @ B)
Rule: (m×n) · (n×p) → (m×p)
2. Determinant ([Link])
Concept
Scalar value representing matrix properties (area/volume, invertibility).
( )
det
a b
c d
=ad−bc
Example:
A = [Link]([[1,2],
[3,4]])
print([Link](A)) # -2.0
If determinant = 0 → matrix is not invertible
3. Inverse ([Link])
Concept
Matrix that “undoes” multiplication.
−1
A A=I
Example:
A = [Link]([[1,2],
[3,4]])
A_inv = [Link](A)
print(A_inv)
print([Link](A, A_inv))
Output ≈ Identity matrix
4. Eigenvalues & Eigenvectors
Concept
Special vectors that don’t change direction.
Av=λv
Example:
A = [Link]([[2,0],
[0,3]])
values, vectors = [Link](A)
print(values) # eigenvalues
print(vectors) # eigenvectors
5. Solving Linear Equations
Solve:
Ax = b
Ax=b
Example:
A = [Link]([[2,1],
[1,3]])
b = [Link]([8,13])
x = [Link](A, b)
print(x)
11. Statistics
1. Core Descriptive Statistics
Mean (Average)
n
1
x́= ∑x
n i=1 i
import numpy as np
arr = [Link]([10, 20, 30, 40])
print([Link](arr)) # 25.0
Median (Middle Value)
print([Link](arr)) # 25.0
Standard Deviation
σ=
√ 1
n
∑¿¿
print([Link](arr))
Variance
print([Link](arr))
Min, Max, Range
print([Link](arr))
print([Link](arr))
print([Link](arr)) # range = max - min
Percentiles & Quantiles
Percentile
arr = [Link]([1,2,3,4,5,6,7,8,9])
print([Link](arr, 25)) # Q1
print([Link](arr, 50)) # median
print([Link](arr, 75)) # Q3
Quantile
Quantile
print([Link](arr, 0.25))
Axis-Based Statistics (VERY IMPORTANT)
arr = [Link]([[10,20,30],
[40,50,60]])
axis=0 → column-wise
axis=1 → row-wise
print([Link](arr, axis=0)) # column mean
print([Link](arr, axis=1)) # row mean
Correlation & Covariance (Advanced)
Covariance
x = [Link]([1,2,3])
y = [Link]([2,4,6])
print([Link](x, y))
Correlation Coefficient
print([Link](x, y))
👉 Values:
+1 → perfect positive
0 → no relation
-1 → negative
6. Z-Score (Standardization)
Used in ML & statistics:
x−x́
z=
σ
arr = [Link]([10, 20, 30, 40])
z = (arr - [Link](arr)) / [Link](arr)
print(z)
MATPLOTLIB
Matplotlib is one of the most popular plotting libraries in Python. It’s used to create static,
animated, and interactive visualizations like line graphs, bar charts, histograms, and more.
A Python library for data visualization
Works well with libraries like NumPy and Pandas
Provides full control over plot appearance
1. LINE PLOT
A line plot in Matplotlib is used to show trends or changes over time.
It connects data points using straight lines.
Basic Syntax
import [Link] as plt
[Link](x, y)
[Link]()
Where:
x → values on x-axis
y → values on y-axis
Adding Title and Labels
[Link]("Graph Title")
[Link]("X-axis")
[Link]("Y-axis")
Adding Marker
Markers show exact data points.
[Link](x, y, marker='o')
Common markers:
'o' → circle
'*' → star
's' → square
'^' → triangle
Changing Line Style
[Link](x, y, linestyle='--')
Styles:
'-' → solid
'--' → dashed
':' → dotted
'-. ' → dash-dot
Changing Color
[Link](x, y, color='red')
Example
import [Link] as plt
x = [1,2,3,4,5]
y1 = [10,20,15,25,30]
y2=[5,10,15,20,25]
line1=[Link](x,y1,label='Class A',color='green',linestyle='--',marker='o')
line2=[Link](x,y2,label='Class B',color='orange',linestyle='-.',marker='^')
[Link]("Student Marks")
[Link]("Test Number")
[Link]("Marks")
[Link]()
[Link]()
Output is:
2. BOX PLOT
A boxplot (box-and-whisker plot) is used to visualize:
spread of data
median
quartiles
outliers
It is very useful in statistics and data analysis.
Basic Syntax
[Link](data)
Parts of a Boxplot
A boxplot contains:
Part Meaning
Bottom whisker Minimum non-outlier
Bottom of box Q1
Middle line Median (Q2)
Top of box Q3
Top whisker Maximum non-outlier
Dots outside Outliers
Quartiles
Quartiles divide data into 4 parts.
IQR=Q 3−Q1
Outlier limits:
Q1−1.5 (IQR)
Q3 +1.5( IQR)
Values outside these limits become outliers.
Important Parameters
Example
import numpy as np
import [Link] as plt
data = [Link](1,100,50)
[Link](data)
[Link]()
Output is