0% found this document useful (0 votes)
2 views39 pages

Unit 4 Numpy Notes

NumPy is an open-source Python library that efficiently handles large multi-dimensional arrays and matrices, providing a variety of mathematical functions. It enhances performance compared to Python's built-in lists, and serves as the foundation for many libraries in data science and machine learning. Key features include ndarray for array handling, broadcasting for operations on different shapes, and various mathematical functions, making it essential for applications in data analysis, machine learning, and scientific computing.

Uploaded by

snehitha0405
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views39 pages

Unit 4 Numpy Notes

NumPy is an open-source Python library that efficiently handles large multi-dimensional arrays and matrices, providing a variety of mathematical functions. It enhances performance compared to Python's built-in lists, and serves as the foundation for many libraries in data science and machine learning. Key features include ndarray for array handling, broadcasting for operations on different shapes, and various mathematical functions, making it essential for applications in data analysis, machine learning, and scientific computing.

Uploaded by

snehitha0405
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-4 NUMPY

What is NumPy?
NumPy (short for Numerical Python) is an open-source Python library designed to handle
large multi-dimensional arrays and matrices efficiently. It also provides a wide variety of
mathematical functions to operate on these arrays.
NumPy is widely used in data science, machine learning, scientific computing, and
engineering applications due to its speed, versatility, and ease of use.

Why Use NumPy?


Python’s built-in lists and loops are slow for large data. NumPy provides:
 Better performance
 Cleaner syntax
 Powerful operations on entire datasets without writing explicit loops
It forms the foundation for many other libraries:
 Pandas: Data analysis
 SciPy: Scientific computing
 Scikit-learn: Machine learning
 TensorFlow / PyTorch: Deep learning

Key Features of NumPy (Detailed Theory)


Feature Description

Core data structure in NumPy. It is much faster and more efficient


[Link](N-
than Python lists. Supports arrays of any dimension (1D, 2D, 3D,
dimensional array)
etc.).

Allows operations between arrays of different shapes and dimensions


2. Broadcasting
without manual looping. Saves time and lines of code.

[Link] Enables fast, element-wise operations over entire arrays using simple
operations syntax like a + b, a * 2, etc., eliminating the need for for-loops.

NumPy provides built-in functions like sum, mean, median, std, dot,
[Link]
exp, log, sqrt, etc., to perform complex mathematical calculations on
functions
arrays.

[Link] Includes matrix operations like multiplication (dot, matmul),


Feature Description

inversion, determinant calculation, solving linear equations,


Support
eigenvalues, etc., used in engineering, physics, ML, etc.

[Link] provides functions to generate random numbers,


6. Random Number
samples from distributions (uniform, normal, binomial, etc.), and is
Generation
widely used in simulations and machine learning.

Advantages of NumPy
 Speed: NumPy arrays are implemented in C, which makes them significantly faster
than native Python lists.
 Memory Efficient: Requires less memory and storage for the same data.
 Convenient Syntax: Supports slicing, masking, filtering, and reshaping easily.
 Interoperability: Can integrate with C, C++, Fortran, and other Python libraries.
 Extensibility: Forms the foundation for advanced libraries in AI/ML.

Real-World Applications
 Data Analysis: NumPy is the core of Pandas, which is used for cleaning and
manipulating large datasets.
 Machine Learning: Libraries like Scikit-learn, TensorFlow use NumPy internally for
data manipulation.
 Image Processing: Images are stored as NumPy arrays; useful in OpenCV, PIL.
 Scientific Simulations: Physics, chemistry, and engineering simulations use NumPy
arrays for computation.
 Finance: Analyzing stock data, calculating returns, moving averages, etc.

1D NumPy Array
A 1D array is like a regular list.
Example:
import numpy as np
arr1d = [Link]([10, 20, 30, 40])
print(arr1d)
Line 1: import numpy as np
This imports the NumPy library and gives it an alias (np), which is a common convention in
Python.
Purpose:
 You need to import NumPy to use its powerful array and math tools.
 Instead of writing [Link](...) every time, you can just write [Link](...).
Line 2: arr1d = [Link]([10, 20, 30, 40])
This creates a 1-dimensional NumPy array using a Python list [10, 20, 30, 40].

 [Link](...) converts the list into a NumPy array object.


 The resulting array is stored in the variable arr1d.
Key Points:
 Shape: (4,) → 4 elements in one dimension
 Dimension: 1D
 Indexing: arr1d[0] gives 10

2D NumPy Array
A 2D array is like a matrix (rows × columns).
Example:
arr2d = [Link]([[1, 2, 3],
[4, 5, 6]])
print(arr2d

Step-by-Step Explanation
import numpy as np
 This imports the NumPy library and gives it the short name np.
 It's required to use NumPy functions like [Link]().
arr2d = [Link]([[1, 2, 3], [4, 5, 6]])
This line creates a 2-dimensional NumPy array (also called a matrix).

Breakdown:
 You’re passing a nested list: [[1, 2, 3], [4, 5, 6]]
 NumPy converts it into a 2D array with:
o 2 rows
o 3 columns
Key Points:
 Shape: (2, 3) → 2 rows, 3 columns
 Dimension: 2D
 Indexing: arr2d[1, 2] gives 6

3D NumPy Array
A 3D array is like a collection of matrices (like a cube).
Example:
arr3d = [Link]([
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
])
print(arr3d)

Step-by-Step Explanation
arr3d = [Link]([...])
This creates a 3-dimensional NumPy array.
The structure here is:
[
[ [1, 2], [3, 4] ],
[ [5, 6], [7, 8] ]
]
Let’s break it down:
 There are 2 blocks (also called "depth layers" or "matrices")
 Each block has 2 rows
 Each row has 2 columns
So the shape is: (2, 2, 2)
 2 blocks (depth)
 2 rows per block
 2 elements per row

Key Points:
 Shape: (2, 2, 2)
o 2 blocks (depth)
o Each block has 2 rows and 2 columns
 Dimension: 3D
 Indexing: arr3d[1, 0, 1] gives 6

NumPy array. Attributes:

These attributes describe the structure, type, and memory usage of a NumPy array.

1. ndim → Number of Dimensions


Tells how many dimensions (or axes) the array has.
 A 1D array is a line of elements.
 A 2D array is a table (rows × columns).
 A 3D array is like a cube or a stack of 2D tables.
Example:
import numpy as np
a = [Link]([1, 2, 3]) # 1D array
print([Link]) # Output: 1

b = [Link]([[1, 2], [3, 4]]) # 2D array


print([Link]) # Output: 2

2. shape → Shape of the Array


Tells how many elements are in each dimension.
It returns a tuple: (rows, columns) for 2D, etc.
Example:
b = [Link]([[1, 2], [3, 4]])
print([Link]) # Output: (2, 2) → 2 rows, 2 columns
Think of it like:
[ [1, 2],
[3, 4] ]

3. size → Total Number of Elements


Total count of all elements in the array.
Example:
b = [Link]([[1, 2], [3, 4]])
print([Link]) # Output: 4 → (2 × 2)

4. dtype → Data Type of Array Elements


Shows what type of numbers are stored in the array:
e.g., int32, float64, bool, etc.

Example:
a = [Link]([1, 2, 3])
print([Link]) # Output: int64

b = [Link]([1.5, 2.5])
print([Link]) # Output: float64
NumPy Array Functions –

1. [Link](shape)
Definition:
Creates an array filled with zeros.
Example:
import numpy as np
a = [Link]((2, 3))
print(a)
Explanation:
 [Link]((2, 3)): creates a 2x3 matrix of 0s.
 a stores the array.
 print(a): prints the result.
Output:
[[0. 0. 0.]
[0. 0. 0.]]

2. [Link](shape)
Definition:
Creates an array filled with ones.
Example:
a = [Link]((3, 2))
print(a)
Explanation:
 (3, 2) → 3 rows, 2 columns.
 All values are 1.
Output:
[[1. 1.]
[1. 1.]
[1. 1.]]
3. [Link](shape, fill_value)
Definition:
Creates an array filled with a specific value.
Example:
a = [Link]((2, 3), 7)
print(a)
Explanation:
 (2, 3) is shape.
 7 is the fill value.
Output:
[[7 7 7]
[7 7 7]]

4. [Link](start, stop, num)


Definition:
Generates evenly spaced values from start to stop.
Example:
a = [Link](0, 1, 5)
print(a)
Explanation:
 Start = 0, Stop = 1.
 Generates 5 values evenly spaced.
Output:
[0. 0.25 0.5 0.75 1. ]

5. [Link](start, stop, step)


Definition:
Creates numbers from start to stop (exclusive), with a step.
Example:
a = [Link](1, 10, 2)
print(a)
Explanation:
 Starts at 1, ends before 10, step size = 2.
Output:
[1 3 5 7 9]

6. [Link](array)
Definition:
Returns a sorted copy of an array.
Example:
a = [Link]([4, 2, 8, 1])
print([Link](a))
Explanation:
 [Link]() returns a new sorted array (does not change the original).
Output:
[1 2 4 8]

7. [Link](n)
Definition:
Creates an n x n identity matrix (1s on diagonal).
Example:
a = [Link](3)
print(a)
Explanation:
 Diagonal is all 1s, others 0.
Output:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

8. [Link] module
Definition:
Used to generate random numbers.
Example: [Link]()
a = [Link](2, 2)
print(a)
Explanation:
 Generates random float numbers in [0, 1).
 Shape is (2, 2).
Output: (varies every time)
[[0.45 0.89]
[0.67 0.12]]

9. [Link](array)
Definition:
Shuffles the array in place along the first axis.
Example:
a = [Link]([1, 2, 3, 4, 5])
[Link](a)
print(a)
Explanation:
 shuffle() randomly reorders elements of a.
Output:
[3 1 4 2 5] # Example; changes each time

10. [Link](array)
Definition:
Returns sorted unique elements from the array.
Example:
a = [Link]([1, 2, 2, 3, 3, 3])
print([Link](a))
Explanation:
 Removes duplicates and sorts.
Output: [1 2 3]

NumPy Aggregation & Statistical Functions

1. [Link](array)
Definition:
Returns the sum of all elements in the array.
Example:
import numpy as np
arr = [Link]([1, 2, 3, 4])
print([Link](arr))
Explanation:
 [Link]([1, 2, 3, 4]) creates a 1D array.
 [Link](arr) adds all elements: 1+2+3+4 = 10.
Output: 10

2. [Link](array)
Definition:
Returns the average (mean) of all elements.
Example:
arr = [Link]([1, 2, 3, 4])
print([Link](arr))
Explanation:
 Mean = (1+2+3+4)/4 = 2.5.
Output: 2.5

3. [Link](array)
Definition:
Returns the standard deviation of the array elements.
Example:
arr = [Link]([1, 2, 3, 4])
print([Link](arr))
Explanation:
 Measures how much values deviate from the mean.
 Lower std → values are close to the mean.
Output: ≈ 1.118

4. [Link](array)
Definition:
Returns the median (middle value) of the array.
Example:
arr = [Link]([1, 3, 2, 4])
print([Link](arr))
Explanation:
 Sorted: [1, 2, 3, 4]
 Median = average of middle two = (2+3)/2 = 2.5
Output: 2.5

5. [Link](array)
Definition:
Returns the variance – the average of squared differences from the mean.
Example:
arr = [Link]([1, 2, 3, 4])
print([Link](arr))
Explanation:
 Mean = 2.5
 Variance = average of [(1–2.5)², (2–2.5)², …]
 = 1.25
Output: 1.25

6. [Link](array)
Definition:
Returns the smallest value in the array.
Example:
arr = [Link]([3, 7, 2, 9])
print([Link](arr))
Output: 2

7. [Link](array)
Definition:
Returns the largest value in the array.
Example:
arr = [Link]([3, 7, 2, 9])
print([Link](arr))
Output: 9

Element-wise Operations & Comparisons

1. Element-wise Arithmetic Operations

[Link](array1, array2)
Definition: Adds corresponding elements.
Example:
import numpy as np
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
result = [Link](a, b)
print(result)

Explanation:
 [1+4, 2+5, 3+6] → [5, 7, 9]
Output: [5 7 9]

b. [Link](array1, array2)
Definition: Subtracts elements of array2 from array1.
result = [Link](a, b)
print(result)
Output: [-3 -3 -3]

c. [Link](array1, array2)
Definition: Multiplies corresponding elements.
result = [Link](a, b)
print(result)
Output: [4 10 18]

[Link](array1, array2)
Definition: Divides elements of array1 by array2.
result = [Link](a, b)
print(result)
Output: [0.25 0.4 0.5]

e. [Link](array1, array2)
Definition: Computes the remainder (modulo) element-wise.
a = [Link]([10, 20, 30])
b = [Link]([3, 7, 9])
result = [Link](a, b)
print(result)
Output: [1 6 3]

2. Element-wise Comparison Operations


<, >, <=, >=, ==, !=
Definition: Returns a boolean array comparing each element.
a = [Link]([1, 2, 3])
b = [Link]([2, 2, 2])
print(a < b) # [True False False]
print(a >= b) # [False True True]

Explanation:
Compares a[i] with b[i] for each i.

3. Rounding Functions
a. [Link](array, decimals)
Definition: Rounds elements to the given decimal places.
a = [Link]([1.234, 5.678])
print([Link](a, 1))
Output: [1.2 5.7]

[Link](array)
Definition: Rounds down to nearest integer.
a = [Link]([1.9, 2.3])
print([Link](a))
Output: [1. 2.]

[Link](array)
Definition: Rounds up to nearest integer.
print([Link](a))
Output: [2. 3.]

[Link](array)
Definition: Truncates (removes decimal part).
print([Link](a))
Output: [1. 2.]

What is Slicing?
Slicing allows you to extract parts of a sequence (like lists, strings, or NumPy arrays) using
this syntax:
sequence[start:stop:step]
Breakdown:
 start → index to begin from (inclusive)
 stop → index to stop at (exclusive)
 step → how many steps to skip
If you leave any of these blank, Python uses defaults:
 start = 0
 stop = len(sequence)
 step = 1

Example 1: Slicing a Python List

my_list = [10, 20, 30, 40, 50, 60]


slice1 = my_list[1:4]
print(slice1)

Line-by-Line Explanation:
1. my_list = [10, 20, 30, 40, 50, 60] → A list of 6 elements.
2. my_list[1:4] → Starts at index 1 (20) and goes up to index 3 (40).
o Does not include index 4 (50)
3. Output: [20, 30, 40]

Example 2: Slicing with Step


my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8]
print(my_list[::2]) # Even index elements

Explanation:
 start: blank → start from 0
 stop: blank → go till end
 step = 2 → pick every 2nd element
Output:
[0, 2, 4, 6, 8]

Example 3: Slicing with Negative Indexes


my_list = [10, 20, 30, 40, 50]
print(my_list[-3:-1])
Explanation:
 -3 → 3rd from end (30)
 -1 → 1st from end, exclusive (50 not included)
Output:
[30, 40]

Example 4: Reversing a List


print(my_list[::-1])
Explanation:
 step = -1 → reverses the list
Output:
[50, 40, 30, 20, 10]

Example 5: Slicing NumPy Arrays


import numpy as np
arr = [Link]([10, 20, 30, 40, 50])
print(arr[1:4])
Works the same as lists:
 Output: [20 30 40]

Example 6: 2D NumPy Array Slicing


arr2d = [Link]([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(arr2d[0:2, 1:3])
Explanation:
 0:2 → Rows 0 and 1
 1:3 → Columns 1 and 2
Output:
[[2 3]
[5 6]]

Slicing a 2D NumPy Array


A 2D array is like a matrix (rows × columns).

Example 1: Basic 2D Array


import numpy as np

arr2d = [Link]([
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
])
📊 Visual Structure:
Col 0 Col 1 Col 2

Row 0 10 20 30

Row 1 40 50 60
Col 0 Col 1 Col 2

Row 2 70 80 90

Example 2: Slice a block


print(arr2d[0:2, 1:3])
Line-by-Line Explanation:
 0:2 → Rows 0 and 1 (up to, but not including, row 2)
 1:3 → Columns 1 and 2 (up to, not including column 3)
Result:
[[20 30]
[50 60]]

Example 3: Select all rows, first column


print(arr2d[:, 0])
Explanation:
 : → All rows
 0 → First column only
Output:
[10 40 70]

Example 4: Select last row, all columns


print(arr2d[-1, :])
Explanation:
 -1 → Last row
 : → All columns
Output:
[70 80 90]
Slicing a 3D NumPy Array
A 3D array is like a collection of matrices (blocks of rows × columns).

Example 1: Create a 3D Array


arr3d = [Link]([
[[1, 2, 3],
[4, 5, 6]],

[[7, 8, 9],
[10, 11, 12]]
])
Structure:
 Shape = (2, 2, 3)
 2 blocks (depths), each 2 rows × 3 columns

Block 0:
[[1 2 3]
[4 5 6]]

Block 1:
[[ 7 8 9]
[10 11 12]]

Example 2: Access Block 1

print(arr3d[1])
Output:
[[ 7 8 9]
[10 11 12]]
Example 3: Access value 11
print(arr3d[1, 1, 1])
Explanation:
 Block 1 → second 2D array
 Row 1 → [10, 11, 12]
 Column 1 → 11
Output:
11

Example 4: Slice all blocks, last row, first column


print(arr3d[:, 1, 0])
Explanation:
 : → All blocks
 1 → Second row
 0 → First column
Output:
[ 4 10]

Example 5: Extract subarray from all blocks


print(arr3d[: , :, 1:])
Explanation:
 : → All blocks
 : → All rows
 1: → Columns from index 1 to end
Output:
[[[ 2 3]
[ 5 6]]

[[ 8 9]
[11 12]]]
What is Linear Algebra?
Linear algebra deals with vectors, matrices, and systems of linear equations. NumPy provides
a special module for this:
import [Link]
Or use:
from numpy import linalg as LA

Common NumPy Linear Algebra Functions


Function Description

[Link](a, b) Matrix or dot product

[Link](a, b) Matrix multiplication

[Link](a) Inverse of matrix

[Link](a) Determinant of matrix

[Link](a) Eigenvalues and eigenvectors

[Link](A, b) Solves Ax = b

[Link](a) Vector/matrix norm (magnitude)

[Link](a) Transpose of matrix

import numpy as np

# Step 1: Define a 2x2 matrix A and vector b


A = [Link]([[2, 1],
[1, 3]])

b = [Link]([8, 13])

# Step 2: Solve Ax = b
x = [Link](A, b)
# Step 3: Compute the inverse of A
A_inv = [Link](A)

# Step 4: Verify the solution using dot product


check = [Link](A, x)

# Step 5: Calculate determinant of A


det = [Link](A)

# Step 6: Find eigenvalues and eigenvectors


eigenvalues, eigenvectors = [Link](A)

# Step 7: Compute the norm (length) of vector b


b_norm = [Link](b)

# Step 8: Transpose of matrix A


A_T = A.T

# Display results
print("Matrix A:\n", A)
print("Vector b:", b)
print("Solution x:", x)
print("Inverse of A:\n", A_inv)
print("Verification Ax:", check)
print("Determinant of A:", det)
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:\n", eigenvectors)
print("Norm of b:", b_norm)
print("Transpose of A:\n", A_T)
Line-by-Line Explanation
Step 1: Define Matrix and Vector
A = [Link]([[2, 1],
[1, 3]])
b = [Link]([8, 13])
 A is a 2×2 matrix
 b is a vector in the system Ax = b

Step 2: Solve the System Ax = b


x = [Link](A, b)
 Uses matrix algebra to solve for x
 Internally, it avoids calculating the inverse for numerical stability
Output:
x = [3. 2.]
2*3 + 1*2 = 8
1*3 + 3*2 = 13

Step 3: Inverse of Matrix


A_inv = [Link](A)
 Computes A⁻¹, such that A @ A⁻¹ = I (identity)
Output:
[[ 0.6 -0.2]
[-0.2 0.4]]

Step 4: Verify Ax = b
check = [Link](A, x)
 Calculates matrix multiplication: A * x → should equal b
Output:
[ 8. 13.]
Step 5: Determinant of A
det = [Link](A)
 det(A) tells us if matrix is invertible (det ≠ 0)
Output:
5.0

Step 6: Eigenvalues and Eigenvectors


eigenvalues, eigenvectors = [Link](A)
 Solves for:
o λ (eigenvalues)
o v (eigenvectors)
Output (example):
Eigenvalues: [1.3819, 3.6180]
Eigenvectors:
[[ -0.8507 -0.5257 ]
[ 0.5257 -0.8507 ]]

Step 7: Norm (Length) of Vector


b_norm = [Link](b)
 Computes the magnitude of b using:
√(8² + 13²)
Output:
15.2643

Step 8: Transpose of Matrix


A_T = A.T
 Transposes the matrix: rows ↔ columns
Output:
[[2 1]
[1 3]]
Line-by-Line Explanation
Step 1: Define Matrix and Vector
A = [Link]([[2, 1],
[1, 3]])
b = [Link]([8, 13])
 A is a 2×2 matrix
 b is a vector in the system Ax = b
Step 2: Solve the System Ax = b
x = [Link](A, b)
 Uses matrix algebra to solve for x
 Internally, it avoids calculating the inverse for numerical stability
Output:
x = [3. 2.]
Which means:
markdown
2*3 + 1*2 = 8
1*3 + 3*2 = 13

Step 3: Inverse of Matrix


A_inv = [Link](A)
 Computes A⁻¹, such that A @ A⁻¹ = I (identity)
Output:
[[ 0.6 -0.2]
[-0.2 0.4]]

Step 4: Verify Ax = b
check = [Link](A, x)
 Calculates matrix multiplication: A * x → should equal b
Output:
[ 8. 13.]

Step 5: Determinant of A
det = [Link](A)
 det(A) tells us if matrix is invertible (det ≠ 0)
Output:
5.0

Step 6: Eigenvalues and Eigenvectors


eigenvalues, eigenvectors = [Link](A)
 Solves for:
o λ (eigenvalues)
o v (eigenvectors)
Output (example):
Eigenvalues: [1.3819, 3.6180]
Eigenvectors:
[[ -0.8507 -0.5257 ]
[ 0.5257 -0.8507 ]]

Step 7: Norm (Length) of Vector


b_norm = [Link](b)
 Computes the magnitude of b using:
√(8² + 13²)
Output:
15.2643

Step 8: Transpose of Matrix


A_T = A.T
 Transposes the matrix: rows ↔ columns
Output:
[[2 1]
[1 3]]

Broadcasting
Broadcasting is a NumPy feature that allows arithmetic operations on arrays of different
shapes and sizes without writing loops.
It "broadcasts" the smaller array across the larger one so their shapes match temporarily for
the operation.

Why Is Broadcasting Useful?


 Saves time and memory
 Replaces complex loops with simple syntax
 Makes code faster and more readable

Broadcasting Rules
For two arrays to be broadcast together:
1. Compare their shapes from right to left.
2. Dimensions are compatible if:
o They are equal, OR
o One of them is 1
If compatible, NumPy stretches the smaller array across the larger one during the operation.

Example 1: Add Scalar to Array


import numpy as np

a = [Link]([1, 2, 3])
b = 10
result = a + b
print(result)
Explanation:
 a has shape (3,)
 b is a scalar → treated as (1,) → broadcasts to match shape
Output:
[11 12 13]

Example 2: Add 1D to 2D Array


a = [Link]([[1, 2, 3],
[4, 5, 6]])
b = [Link]([10, 20, 30])
result = a + b
print(result)
Explanation:
 [Link] = (2, 3)
 [Link] = (3,) → treated as (1, 3) and broadcasted over rows
Output:
[[11 22 33]
[14 25 36]]

Example 3: Column-wise Broadcasting


a = [Link]([[1, 2, 3],
[4, 5, 6]])

b = [Link]([[10],
[20]])

result = a + b
print(result)
Explanation:
 [Link] = (2, 3)
 [Link] = (2, 1) → broadcasted over columns
Output:
[[11 12 13]
[24 25 26]]

Example 4: Incompatible Shapes (Error)


a = [Link]([[1, 2],
[3, 4]])

b = [Link]([1, 2, 3])

result = a + b # ❌ Incompatible
Output:
ValueError: operands could not be broadcast together with shapes (2,2) (3,)

Broadcasting: 1D and 2D Arrays

Example 1: Add 1D to 2D
import numpy as np
a = [Link]([[1, 2, 3],
[4, 5, 6]]) # shape: (2, 3)
b = [Link]([10, 20, 30]) # shape: (3,)
result = a + b
print(result)
Explanation:
 Shapes: (2, 3) + (3,)
 b is broadcast to (1, 3) → then to (2, 3)
Output:
[[11 22 33]
[14 25 36]]

Example 2: Add Column Vector to 2D


a = [Link]([[1, 2, 3],
[4, 5, 6]]) # shape: (2, 3)

b = [Link]([[10],
[20]]) # shape: (2, 1)

result = a + b
print(result)
Explanation:
 a: shape (2, 3)
 b: shape (2, 1)
 b is broadcast across columns → becomes (2, 3)
Output:
[[11 12 13]
[24 25 26]]

Broadcasting: 1D and 3D Arrays

Example: Add 1D to 3D Array


a = [Link]((2, 3, 4)) # shape: (2, 3, 4)
b = [Link]([10, 20, 30, 40]) # shape: (4,)
result = a + b
print([Link])

Explanation:
 a: (2, 3, 4)
 b: (4,) → treated as (1, 1, 4)
 Broadcasted to (2, 3, 4)
Output:
(2, 3, 4)
Each row of the last dimension gets added element-wise with b.

Broadcasting: 2D and 3D Arrays

Example: Add 2D to 3D
a = [Link]((2, 3, 4)) # shape: (2, 3, 4)
b = [Link]([[10], [20], [30]]) # shape: (3, 1)
result = a + b
print([Link])

Explanation:
 a: (2, 3, 4)
 b: (3, 1) → treated as (1, 3, 1)
 Final result: (2, 3, 4)
Output:
(2, 3, 4)
Each 3×1 block in b is broadcast over the 4 columns of a.

Final Summary: Shapes and Results


Example [Link] [Link] Result shape Notes

1D + 2D (2, 3) (3,) (2, 3) b is broadcast over rows

1D + 3D (2, 3, 4) (4,) (2, 3, 4) b applies to last dim

2D + 3D (2, 3, 4) (3, 1) (2, 3, 4) b reshaped to (1, 3, 1)

❌ Broadcasting Error Example


a = [Link]((2, 3))
b = [Link]((4,))

# This will fail:


result = a + b
Error:
ValueError: operands could not be broadcast together with shapes (2,3) (4,)
Why? Because last dimensions 3 and 4 are not compatible.

Tip for Broadcasting:


Use .reshape() or [Link] to make dimensions align manually.
Example:
a = [Link]([1, 2, 3])
a = a[:, [Link]] # shape: (3, 1)

NumPy shape Attribute

The .shape attribute of a NumPy array tells you the dimensions of the array.
It returns a tuple of integers indicating:
 how many rows,
 how many columns,
 how many "layers" (in 3D or more).

Shape Format
Array Type Shape Example Meaning

1D (4,) 1 row of 4 elements

2D (3, 2) 3 rows, 2 columns

3D (2, 3, 4) 2 blocks of 3×4 arrays

Example 1: 1D Array
import numpy as np
arr1d = [Link]([10, 20, 30, 40])
print("Array:\n", arr1d)
print("Shape:", [Link])

Explanation:
 arr1d has 4 elements in a single row → shape is (4,)
 .shape returns a tuple → one value for 1D
Output:
Array:
[10 20 30 40]
Shape: (4,)

Example 2: 2D Array
arr2d = [Link]([[1, 2, 3],
[4, 5, 6]])
print("Array:\n", arr2d)
print("Shape:", [Link])
Explanation:
 Two rows, three columns → shape is (2, 3)
Output:
Array:
[[1 2 3]
[4 5 6]]
Shape: (2, 3)

Example 3: 3D Array
arr3d = [Link]([
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
])
print("Array:\n", arr3d)
print("Shape:", [Link])
Explanation:
 2 outer arrays (like layers or blocks)
 Each has 2 rows and 2 columns
 → shape is (2, 2, 2)
Output:
Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Shape: (2, 2, 2)
.reshape()?
NumPy .reshape() changes the shape of an existing array without changing its data.
Why use it?
 To prepare data for operations like matrix multiplication, ML models, etc.
 To flatten or expand dimensions for broadcasting or plotting.

Syntax:
[Link](new_shape)
 new_shape is a tuple like (rows, columns)
 The total number of elements must remain the same

Example 1: Reshape 1D to 2D
import numpy as np
a = [Link]([1, 2, 3, 4, 5, 6])
b = [Link]((2, 3))
print("Original shape:", [Link])
print("Reshaped array:\n", b)
print("New shape:", [Link])
Explanation:
 a has shape (6,)
 You reshape it to 2 rows × 3 columns → (2, 3)
 No data is lost or added.
Output:
Original shape: (6,)
Reshaped array:
[[1 2 3]
[4 5 6]]
New shape: (2, 3)

Example 2: Reshape 2D to 3D
a = [Link]([[1, 2, 3],
[4, 5, 6]])

b = [Link]((3, 2, 1))

print("Reshaped shape:", [Link])


print(b)
Explanation:
 Original shape: (2, 3) = 6 elements
 New shape: (3, 2, 1) = 6 elements → valid
Output:
Reshaped shape: (3, 2, 1)
[[[1]
[2]]
[[3]
[4]]
[[5]
[6]]]

Example 4: Flatten a 2D array


a = [Link]([[1, 2, 3],
[4, 5, 6]])

b = [Link](-1) # or [Link]((6,))
print("Flattened:", b)
Output:
Flattened: [1 2 3 4 5 6]

What Are Boolean Masks?


A boolean mask is a NumPy array of True or False values used to filter elements from
another array.
It answers questions like:
 Which values are greater than 10?
 Where is the array negative?
 Where are values even?

Why Use Masks?


 To filter, replace, or select elements
 Makes data analysis efficient and fast (no loops needed)

Basic Example
import numpy as np

a = [Link]([5, 10, 15, 20, 25])

mask = a > 15 # Create mask


print(mask) # [False False False True True]
print(a[mask]) # Use mask to filter values
Explanation:
 a > 15 returns a boolean array
 a[mask] returns only the elements where the mask is True
Output:
[False False False True True]
[20 25]

Example: Boolean Conditions with Operators


a = [Link]([1, 5, 10, 15, 20])

# Filter even numbers


even_mask = a % 2 == 0
print("Even numbers:", a[even_mask])

# Filter values between 5 and 15


between_mask = (a >= 5) & (a <= 15)
print("Between 5 and 15:", a[between_mask])
Notes:
 Use &, |, ~ instead of Python’s and, or, not
 Always wrap comparisons in parentheses
Output:
Even numbers: [10 20]
Between 5 and 15: [5 10 15]

Example: Assigning with Masks


a = [Link]([1, 5, 10, 15, 20])

# Set all values > 10 to 100


a[a > 10] = 100
print(a)
Output:
[ 1 5 10 100 100]
Example: Masking in 2D Arrays
a = [Link]([[1, 2, 3],
[4, 5, 6]])

mask = a % 2 == 0
print("Even elements:", a[mask])
Output:
Even elements: [2 4 6]

You might also like