0% found this document useful (0 votes)
36 views25 pages

Vectorized Array Operations in NumPy (Detailed Explanation)

The document outlines the content covered in Weeks 4 and 5 of a course on Numerical Python (NumPy), focusing on array creation, properties, operations, and advanced topics like multi-dimensional arrays and linear algebra. Week 4 introduces basic operations and array manipulation, while Week 5 delves into advanced techniques such as reshaping, stacking, and statistical functions. Key concepts include creating arrays, performing vectorized operations, and working with file I/O in NumPy.

Uploaded by

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

Vectorized Array Operations in NumPy (Detailed Explanation)

The document outlines the content covered in Weeks 4 and 5 of a course on Numerical Python (NumPy), focusing on array creation, properties, operations, and advanced topics like multi-dimensional arrays and linear algebra. Week 4 introduces basic operations and array manipulation, while Week 5 delves into advanced techniques such as reshaping, stacking, and statistical functions. Key concepts include creating arrays, performing vectorized operations, and working with file I/O in NumPy.

Uploaded by

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

week 4 and Week 5 (Only Numerical Python)

Week 4 & Week 5 - Numerical Python (NumPy)

Numerical Python (NumPy) is a fundamental package for numerical computing in Python. It provides
support for arrays, mathematical operations, and efficient data processing. The course covers NumPy
across multiple lectures.

Week 4: Numerical Python - Introduction & Basic Operations


Lecture 20: Numerical Python - Part I

Introduction to NumPy:

NumPy as a package for numerical computing.

Provides better execution speed and memory optimization compared to built-in Python lists.

Creating Arrays:

Using `np.array()` to create one-dimensional and multi-dimensional arrays.

Specifying data types with the `dtype` argument.

Array Properties:
Checking dimensions using `.ndim` and shape using `.shape`.

Creating arrays with specific values using `np.zeros()`, `np.ones()`, and `np.arange()`.

Data Type Conversion:

Using `.astype()` to change data types.


Example: Converting integer arrays to float arrays​.

Lecture 21: Numerical Python - Part II

Array Operations:
Arithmetic operations (addition, subtraction, multiplication, division).

Element-wise operations and broadcasting.


Indexing and Slicing:

Accessing specific elements in arrays.


Multi-dimensional indexing: `array[row, column]` notation.

Boolean Indexing:
Filtering elements based on conditions.

Example: `array[array > 5]` to get all elements greater than 5​.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/25
Week 5: Advanced Numerical Python
Lecture 22: Numerical Python - Part III

Multi-Dimensional Arrays:

Working with 3D and higher-dimensional arrays.


Assigning values to multi-dimensional arrays.

Fancy Indexing:
Using multiple lists of indices for selection.

Example: `array[[0, 2, 4], [1, 3, 5]]` for advanced selection​.

Lecture 23: Numerical Python - Part IV

Transpose and Reshaping:

`.T` attribute for transposing arrays.

Using `.reshape()` to modify dimensions.


Stacking and Splitting Arrays:

`np.hstack()` and `np.vstack()` for horizontal and vertical stacking.

`np.split()` for breaking arrays into smaller chunks​.

Lecture 24: Numerical Python - Part V

Vectorized Operations:

Performing element-wise operations without loops.

Example: `array1 + array2` instead of using `for` loops.


Random Functions:

Generating random numbers with `np.random`.

Setting random seeds for reproducibility​.

Lecture 25: Numerical Python - Part VI

Linear Algebra with NumPy:

Dot product (`np.dot()`), matrix multiplication, and eigenvalues.

Solving linear equations using `np.linalg.solve()`.


Statistical Functions:

Mean, median, variance, and standard deviation using `np.mean()`, `np.median()`, and
`np.std()`​.

This summary covers Week 4 and Week 5 (Numerical Python) based on the provided course content.
Let me know if you need explanations with code examples! 🚀
Sources

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/25
You've uploaded a Jupyter Notebook (`Untitled7.ipynb`). Do you want me to extract and review the code
related to Numerical Python (NumPy) from the notebook? Let me know if you're looking for any
specific analysis or explanations!🚀

These are the codes of Numerical Python


Answer me questions regarding to topics in NUmerical python using the pdf and codes i shared with
you as i ask you one by one..
understand?

Got it! Ask your questions about Numerical Python, and I'll answer them using the PDF and your
Jupyter Notebook. 🚀

before that
tell me right now what topics and videos are covered in the codes I shared with you ? Can you
please cross as i have not watched all the videos, might have missed a few from the last, i did watch
them in order though.. dont miss a single code

I'll extract the topics and videos covered in your Jupyter Notebook (`Untitled7.ipynb`) and cross-check
them with the PDF syllabus to ensure that no topics are missed. Let me analyze your notebook now. 🚀
Your Jupyter Notebook covers the following Numerical Python (NumPy) topics:

Covered Topics (from your Notebook)

1. Creating NumPy Arrays

`np.array()`, specifying `dtype`


Multi-dimensional arrays

2. Array Properties
`.ndim` (Number of dimensions)
`.shape` (Shape of array)

`.dtype` (Data type of elements)


3. Array Creation Functions
`np.zeros()`, `np.ones()`, `np.arange()`

4. Data Type Conversion (Casting)


Using `.astype()` to convert between data types
5. Mathematical Operations (Vectorized)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/25
Element-wise addition, subtraction, multiplication, and division
6. Indexing and Slicing

1D and 2D array slicing


7. Boolean Indexing
Filtering arrays using conditions (`array[array > value]`)

8. Stacking & Splitting Arrays


`np.hstack()`, `np.vstack()`, `np.split()`

9. Linear Algebra Operations

Matrix multiplication (`np.dot()`)


Eigenvalues, solving equations (`np.linalg.solve()`)

10. Statistical Functions

Mean, median, variance, standard deviation (`np.mean()`, `np.median()`, `np.std()`)

Cross-Check with the PDF

From the PDF syllabus, Numerical Python is covered in:

Week 4:

Numerical Python Part I & II


Week 5:

Numerical Python Part III to VII

Your notebook includes content from all these lectures, meaning you have watched videos in
sequence but might have missed some parts of Week 5 (Numerical Python Part VII).

Next Step

If you want, I can extract more details to check exactly which sections of Week 5 (Part VII) are missing.
Let me know how you'd like to proceed! 🚀 ​

i just did watch till numerical python part 5


lets do stuff till there only, forget the extra i have a test tomorrow

Got it! We'll stick to Numerical Python Part I - V for your test prep. Ask me your questions, and I'll
answer them using your PDF and Jupyter Notebook. 🚀

Working with file Numerical Python

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/25
In Numerical Python (NumPy), working with files typically involves saving and loading binary (NumPy-
specific format) or text (CSV, TXT) files. Let's go over the key methods based on your PDF and Jupyter
Notebook.

1. Saving and Loading NumPy Arrays (Binary Format - `.npy`)

NumPy provides efficient ways to store arrays in binary format using `.npy` files.

Saving an array

python

import numpy as np

arr = np.array([1, 2, 3, 4, 5])


np.save('array_file.npy', arr) # Saves arr to a binary file

Loading an array

python

loaded_arr = np.load('array_file.npy') # Loads the saved array


print(loaded_arr) # Output: [1 2 3 4 5]

2. Saving and Loading Multiple Arrays (`.npz` format)

If you need to save multiple arrays in a single file, use `.npz` format.

Saving multiple arrays

python

arr1 = np.array([10, 20, 30])


arr2 = np.array([[1, 2, 3], [4, 5, 6]])

np.savez('multi_arrays.npz', first=arr1, second=arr2)

Loading multiple arrays

python

loaded = np.load('multi_arrays.npz')
print(loaded['first']) # Output: [10 20 30]
print(loaded['second']) # Output: [[1 2 3] [4 5 6]]

3. Working with Text Files (`.txt` and `.csv`)

NumPy can save and read text files (CSV or TXT) easily.

Saving an array to a text file

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/25
python

np.savetxt('data.txt', arr, delimiter=',') # Saves as comma-separated values

Loading a text file

python

loaded_text = np.loadtxt('data.txt', delimiter=',')


print(loaded_text)

What to Focus on for Your Test

Know how to use `np.save()` and `np.load()` for binary files.


Understand `np.savez()` for saving multiple arrays.

Be comfortable with `np.savetxt()` and `np.loadtxt()` for text files.


Be ready for syntax-based questions (e.g., difference between `.npy` and `.csv`).

Let me know if you need examples from your Jupyter Notebook! 🚀

N-dimensional array objects

N-Dimensional Array Objects in NumPy

NumPy provides N-dimensional arrays (ndarrays) that allow efficient storage and manipulation of
multi-dimensional data.

1. Creating N-Dimensional Arrays


NumPy arrays can have 1D, 2D, 3D, or higher dimensions.

1D Array (Vector)

python

import numpy as np

arr1D = np.array([1, 2, 3, 4, 5])


print(arr1D.ndim) # Output: 1 (1D array)

2D Array (Matrix)

python

arr2D = np.array([[1, 2, 3], [4, 5, 6]])

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/25
print(arr2D.ndim) # Output: 2

3D Array (Tensor)

python

arr3D = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])


print(arr3D.ndim) # Output: 3

2. Checking Array Properties


Property Description Example
`ndim` Number of dimensions `arr.ndim`

`shape` Tuple representing the array dimensions `arr.shape`

`size` Total number of elements `arr.size`


`dtype` Data type of elements `arr.dtype`

Example:

python

arr = np.array([[1, 2, 3], [4, 5, 6]])


print(arr.shape) # Output: (2, 3) → 2 rows, 3 columns
print(arr.size) # Output: 6 → Total elements
print(arr.dtype) # Output: int64 (depends on system)

3. Reshaping N-Dimensional Arrays


You can convert 1D → 2D, 2D → 3D, etc. using `reshape()`.

python

arr = np.arange(12) # Creates a 1D array from 0 to 11


arr2D = arr.reshape(3, 4) # Converts to 2D array with 3 rows, 4 columns
print(arr2D.shape) # Output: (3, 4)

You can also flatten arrays:

python

arr_flat = arr2D.flatten() # Converts back to 1D

4. Special Functions for N-D Arrays


`np.zeros((x, y, z))` → Creates an N-D array filled with zeros.
`np.ones((x, y, z))` → Creates an N-D array filled with ones.

`np.eye(n)` → Creates an identity matrix.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/25
Example:

python

np.zeros((2, 3, 4)) # 3D array with all zeros (2 blocks, 3 rows, 4 columns)

Key Takeaways for Your Test

✅ Know how to create 1D, 2D, and 3D arrays


✅ Understand , , , and
✅ Be comfortable with reshaping (
`ndim` `shape` `size` `dtype`
)
✅ Practice flattening (
`reshape()`
) and special functions (
`flatten()` `zeros()`, `ones()`)

Let me know if you need more details! 🚀

arange

`np.arange()` in NumPy

`np.arange()` is used to create an array with a range of values. It works similarly to Python’s `range()`
function but returns a NumPy array instead of a list.

1. Syntax
python

np.arange(start, stop, step, dtype=None)

start (optional): Starting value (default is `0`)

stop (required): End value (excluded)

step (optional): Difference between values (default is `1`)


dtype (optional): Data type of the array elements

2. Examples of `np.arange()`
Basic Usage

python

import numpy as np

arr = np.arange(5)
print(arr)
# Output: [0 1 2 3 4] (default start = 0, step = 1)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/25
Specifying `start` and `stop`

python

arr = np.arange(3, 10)


print(arr)
# Output: [3 4 5 6 7 8 9] (starts from 3, stops before 10)

Using `step`

python

arr = np.arange(2, 20, 3)


print(arr)
# Output: [ 2 5 8 11 14 17] (increments by 3)

Using `dtype`

python

arr = np.arange(1, 5, dtype=float)


print(arr)
# Output: [1. 2. 3. 4.] (all elements as float)

Negative Step (Descending Order)

python

arr = np.arange(10, 1, -2)


print(arr)
# Output: [10 8 6 4 2] (decreases by 2)

3. Difference Between `np.arange()` and `np.linspace()`


Both create sequences, but `np.linspace()` specifies the number of elements, whereas `np.arange()`
uses a fixed step size.

python

np.arange(1, 10, 3) # Output: [1 4 7]


np.linspace(1, 10, 3) # Output: [ 1. 5.5 10.] (3 evenly spaced numbers)

Key Takeaways for Your Test



`np.arange(start, stop, step, dtype)`
is included, is excluded
✅ controls the difference between numbers
`start` `stop`

✅ Works with negative steps for reverse sequences


`step`

✅ Use `dtype`to control data type

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/25
Let me know if you need more examples! 🚀

dtype , astype, array function, shorthand type codes

1. `dtype` (Data Type) in NumPy

Every NumPy array has a specific data type (`dtype`), which defines the type of values stored in it.

Checking `dtype` of an Array

python

import numpy as np

arr = np.array([1, 2, 3, 4])


print(arr.dtype)
# Output: int32 or int64 (depends on system)

Specifying `dtype` While Creating an Array

python

arr = np.array([1, 2, 3], dtype=float)


print(arr)
# Output: [1. 2. 3.] (stored as float)

Common `dtype` Values

`dtype` Description

`int32`, `int64` Integer (32-bit, 64-bit)


`float32`, `float64` Floating-point (32-bit, 64-bit)

`complex64`, `complex128` Complex numbers


`bool` Boolean (`True`, `False`)

`str` String

`object` Python objects

2. `astype()` - Type Conversion

You can convert an array to a different type using `.astype()`.

Example: Converting Integer to Float

python

arr = np.array([1, 2, 3])


arr_float = arr.astype(float)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/25
print(arr_float)
# Output: [1. 2. 3.]

Example: Converting Float to Integer

python

arr = np.array([1.7, 2.9, 3.2])


arr_int = arr.astype(int)
print(arr_int)
# Output: [1 2 3] (decimals removed, not rounded)

Example: Converting Strings to Numbers

python

arr_str = np.array(['1', '2', '3'])


arr_num = arr_str.astype(int)
print(arr_num)
# Output: [1 2 3]

3. `array()` Function

The `np.array()` function is used to create arrays in NumPy.

Creating 1D Array

python

arr = np.array([1, 2, 3, 4])

Creating 2D Array

python

arr2D = np.array([[1, 2, 3], [4, 5, 6]])

Creating Array with Specified `dtype`

python

arr = np.array([1, 2, 3], dtype=float)

4. Shorthand Type Codes

Instead of writing full names like `int64` or `float32`, NumPy provides short type codes.

Type Code Data Type


`'i'` Integer

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/25
Type Code Data Type
`'f'` Float
`'b'` Boolean

`'U'` Unicode String


`'O'` Object

Example Using Shorthand Type Codes

python

arr = np.array([1, 2, 3], dtype='f')


print(arr.dtype) # Output: float32

Key Takeaways for Your Test

✅ defines the data type of a NumPy array



`dtype`
converts an array to a different type

`.astype()`
creates arrays with optional
✅ Shorthand type codes make specifying types easier
`np.array()` `dtype`

Let me know if you need more details or examples! 🚀

Slicing, Mulitple slicing, no slicing

Slicing in NumPy

Slicing in NumPy allows extracting specific elements from an array using the format:

python

array[start:stop:step]

start → Index to begin slicing (default is `0`)

stop → Index where slicing stops (not included)


step → How many steps to skip (default is `1`)

1. Basic Slicing (1D Array)


python

import numpy as np

arr = np.array([10, 20, 30, 40, 50, 60])


print(arr[1:4])
# Output: [20 30 40] (from index 1 to 3, index 4 is not included)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/25
Using Step Size

python

print(arr[::2])
# Output: [10 30 50] (every second element)

Negative Indexing

python

print(arr[-4:-1])
# Output: [30 40 50] (negative indexing from the end)

2. Multiple Slicing (2D Arrays)


For 2D arrays, slicing is done using `array[row_start:row_stop, col_start:col_stop]`

python

arr2D = np.array([[1, 2, 3, 4],


[5, 6, 7, 8],
[9, 10, 11, 12]])

print(arr2D[0:2, 1:3])
# Output:
# [[2 3]
# [6 7]]

Slicing Rows Only

python

print(arr2D[1:])
# Output:
# [[ 5 6 7 8]
# [ 9 10 11 12]]

Slicing Columns Only

python

print(arr2D[:, 2])
# Output: [3 7 11] (third column from each row)

Skipping Rows & Columns

python

print(arr2D[::2, ::2])
# Output:
# [[ 1 3]
# [ 9 11]]
# (Skipping every second row and column)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/25
3. No Slicing (Selecting Entire Array)
If you want to keep the entire array, you can omit slicing parameters or use `:`.

python

print(arr[:]) # Output: Entire 1D array


print(arr2D[:]) # Output: Entire 2D array
print(arr2D[:, :]) # Output: Same as above, full array

Key Takeaways for Your Test

✅ Basic slicing →
✅ Multi-dimensional slicing →
`array[start:stop:step]`

✅ Negative indexing allows slicing from the end


`array[row_start:row_stop, col_start:col_stop]`

✅ Omitting slicing parameters ( ) selects the entire array


`:`

Let me know if you need more examples! 🚀

lambda functions

Lambda Functions in NumPy

A lambda function (also called an anonymous function) is a small, one-line function defined using the
`lambda` keyword.

1. Syntax of a Lambda Function


python

lambda arguments: expression

`arguments` → Input values

`expression` → Computation to be performed

Example:

python

square = lambda x: x**2


print(square(5))
# Output: 25

2. Using Lambda Functions with NumPy

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/25
Lambda functions are commonly used with NumPy functions like `map()`, `filter()`, and
`vectorize()`.

Example 1: Applying a Lambda Function with `map()`

python

import numpy as np

arr = np.array([1, 2, 3, 4, 5])


squared_arr = list(map(lambda x: x**2, arr))
print(squared_arr)
# Output: [1, 4, 9, 16, 25]

Example 2: Using `np.vectorize()` for Element-wise Lambda Application

Since `map()` is not optimized for NumPy arrays, `np.vectorize()` is a better alternative.

python

vec_func = np.vectorize(lambda x: x**2 + 2*x + 1)


arr = np.array([1, 2, 3, 4])
print(vec_func(arr))
# Output: [ 4 9 16 25]

💡 `np.vectorize()` applies the lambda function to each element without using loops.

Example 3: Filtering Elements with `filter()`

To extract elements that satisfy a condition, `filter()` can be used.

python

filtered = list(filter(lambda x: x % 2 == 0, arr))


print(filtered)
# Output: [2, 4]

🔹 Note: `filter()` returns a filter object, so it must be converted to a list.

Example 4: Lambda with NumPy Operations

Lambda functions can be combined directly with NumPy functions.

python

arr = np.array([10, 20, 30, 40])


result = (lambda x: x / 10)(arr)
print(result)
# Output: [1. 2. 3. 4.]

Key Takeaways for Your Test

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/25
✅ Lambda functions → One-line, anonymous functions using

`lambda`
is the best way to apply lambda to NumPy arrays

`np.vectorize()`
and work but are slower for NumPy arrays
✅ Can be used in mathematical transformations
`map()` `filter()`

Let me know if you need more details! 🚀

shape, reshape, range, arange

1. `shape` in NumPy

The `shape` attribute of a NumPy array returns a tuple representing the dimensions of the array.

Example: Checking `shape`

python

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])


print(arr.shape)
# Output: (2, 3) → 2 rows, 3 columns

Modifying Shape Using `shape`

python

arr.shape = (3, 2)
print(arr)
# Output:
# [[1 2]
# [3 4]
# [5 6]]

🔹 Note: `shape` can directly modify an array if the total number of elements remains the same.

2. `reshape()` in NumPy

The `reshape()` function is used to change the dimensions of an array without modifying its data.

Reshaping a 1D Array to 2D

python

arr = np.arange(6)
reshaped = arr.reshape(2, 3)
print(reshaped)
# Output:
# [[0 1 2]
# [3 4 5]]

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/25
Reshaping a 2D Array to 3D

python

arr = np.arange(12)
reshaped = arr.reshape(2, 3, 2)
print(reshaped)
# Output:
# [[[ 0 1]
# [ 2 3]
# [ 4 5]]
#
# [[ 6 7]
# [ 8 9]
# [10 11]]]

🔹 Note: The total number of elements must remain unchanged.


Using `-1` for Auto Reshaping

python

arr = np.arange(8)
reshaped = arr.reshape(2, -1) # NumPy automatically calculates the second dimension
print(reshaped.shape) # Output: (2, 4)

3. `range()` vs. `arange()`

Function Works in Output Type Allows Float Steps?


`range()` Python List ❌ No
`np.arange()` NumPy NumPy Array ✅ Yes
Using `range()` in Python

python

print(list(range(1, 10, 2)))


# Output: [1, 3, 5, 7, 9]

🔹 Returns a Python list (not a NumPy array).


4. `np.arange()` in NumPy

`np.arange(start, stop, step, dtype)` creates a NumPy array with a specified range.

Basic Usage

python

arr = np.arange(1, 10, 2)


print(arr)
# Output: [1 3 5 7 9]

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/25
Using Float Step

python

arr = np.arange(1, 5, 0.5)


print(arr)
# Output: [1. 1.5 2. 2.5 3. 3.5 4. 4.5]

Using `dtype`

python

arr = np.arange(1, 5, dtype=float)


print(arr)
# Output: [1. 2. 3. 4.]

Key Takeaways for Your Test

✅ gives the dimensions of an array.



`shape`
`reshape()` changes array shape without altering data.
✅ is a Python function (returns a list).

`range()`
`np.arange()` is a NumPy function (returns an array, supports float steps).

Let me know if you need more examples! 🚀

transposing and swapping axes

Transposing and Swapping Axes in NumPy

NumPy provides functions to rearrange the dimensions of arrays using transposing (`.T`) and
swapping axes (`swapaxes()`).

1. Transposing an Array (`.T` or `np.transpose()`)


Transposing means flipping the rows and columns of an array.

Example: Transposing a 2D Array

python

import numpy as np

arr = np.array([[1, 2, 3],


[4, 5, 6]])

print(arr.T)
# Output:
# [[1 4]
# [2 5]
# [3 6]]

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/25
🔹 Rows become columns, and columns become rows.
2. Using `np.transpose()` (More Flexible)

`np.transpose()` can be used for multi-dimensional arrays by specifying axes order.

Example: Transposing a 3D Array

python

arr3D = np.array([[[1, 2], [3, 4]],


[[5, 6], [7, 8]]])

print(np.transpose(arr3D, (1, 0, 2)))


# Output:
# [[[1 2]
# [5 6]]
#
# [[3 4]
# [7 8]]]

🔹 Axes (dimensions) are swapped according to the order given.


3. Swapping Axes (`np.swapaxes()`)
`swapaxes()` is used to swap two specific axes instead of fully transposing.

Example: Swapping Axes in a 3D Array

python

arr3D = np.array([[[1, 2], [3, 4]],


[[5, 6], [7, 8]]])

swapped = np.swapaxes(arr3D, 0, 2) # Swap axis 0 and axis 2


print(swapped.shape)
# Output: (2, 2, 2) (changed from (2, 2, 2), but axes are swapped)

print(swapped)
# Output:
# [[[1 5]
# [3 7]]
#
# [[2 6]
# [4 8]]]

🔹 Only swaps the selected axes, unlike a full transpose.


4. Difference Between `transpose()` and `swapaxes()`

Function Usage Works On Purpose

Transposes rows &


`.T` `array.T` 2D+ Arrays
columns
Any N-D
`np.transpose()` `np.transpose(array, axes)` Reorders all axes
Array

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/25
Function Usage Works On Purpose
`np.swapaxes(array, axis1, Any N-D
`np.swapaxes()` Swaps two specific axes
axis2)` Array

Key Takeaways for Your Test

✅ Transposing ( ) flips rows and columns



`.T`
is more flexible for N-dimensional arrays

`np.transpose()`
swaps only two axes, not the whole array
✅ Use for simple 2D arrays,
`np.swapaxes()`
`.T` for fine control
`swapaxes()`

Let me know if you need more examples! 🚀

Vectorized array operations (explain in detail, dont just refer to the codes i gave you)

Vectorized Array Operations in NumPy (Detailed Explanation)


What are Vectorized Operations?

Vectorized operations in NumPy allow performing element-wise computations without explicit loops.
Instead of using `for` loops (which are slow in Python), NumPy operations apply functions directly to
entire arrays, making computations faster and more efficient.

1. Why Use Vectorized Operations?


🔹 Faster execution – NumPy uses optimized C-based operations under the hood.
🔹 Less code – No need for explicit loops.
🔹 More readable – The operations look like mathematical equations.
`for`

Example: Without Vectorization (Using Loops)

python

import numpy as np

arr1 = np.array([1, 2, 3, 4])


arr2 = np.array([5, 6, 7, 8])

# Without vectorization (using a loop)


result = []
for i in range(len(arr1)):
result.append(arr1[i] + arr2[i])

print(result)
# Output: [6, 8, 10, 12]

🔴 Issue: This method is slow, especially for large arrays.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/25
2. Using Vectorized Operations (Fast & Efficient)
Element-wise Operations

NumPy allows operations to be applied to entire arrays at once.

python

result = arr1 + arr2 # Element-wise addition


print(result)
# Output: [6 8 10 12]

✅ No loops, direct computation!


More Element-wise Operations:

Operation Example Equivalent Math

Addition `arr1 + arr2` A+B


Subtraction `arr1 - arr2` A−B
Multiplication `arr1 * arr2` A×B
Division `arr1 / arr2` A÷B
Power `arr1 ** 2` A2

3. Vectorized Functions (Unary Operations)


These apply mathematical functions element-wise to a NumPy array.

python

arr = np.array([1, 4, 9, 16])

print(np.sqrt(arr)) # Square root


# Output: [1. 2. 3. 4.]

print(np.exp(arr)) # Exponential (e^x)


# Output: [2.718 54.598 8103.08 8.886E06]

✅ No need to use `for` loops, NumPy applies functions directly!

4. Broadcasting in Vectorized Operations


Broadcasting allows NumPy to perform operations between arrays of different shapes without
explicitly reshaping them.

Example 1: Adding a Scalar to an Array

python

arr = np.array([1, 2, 3, 4])


print(arr + 10)
# Output: [11 12 13 14]

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/25
🔹 Each element gets added to `10` automatically.

Example 2: Operating on Arrays with Different Shapes

python

arr1 = np.array([[1, 2, 3], [4, 5, 6]])


arr2 = np.array([1, 2, 3]) # 1D array

print(arr1 + arr2)
# Output:
# [[2 4 6]
# [5 7 9]]

🔹 NumPy broadcasts `arr2` across `arr1`, applying the operation row-wise.

5. Masking (Using Conditions with Arrays)


NumPy allows conditional filtering using vectorized boolean operations.

python

arr = np.array([1, 2, 3, 4, 5, 6])

print(arr[arr > 3])


# Output: [4 5 6] (Extracts values greater than 3)

🔹 No need to use `for` loops for filtering!

6. Dot Product & Matrix Multiplication (Optimized for Speed)


Using `np.dot()` for Dot Product

python

A = np.array([1, 2, 3])
B = np.array([4, 5, 6])

dot_product = np.dot(A, B)
print(dot_product)
# Output: 32 (1*4 + 2*5 + 3*6)

🔹 Much faster than writing manual loops for dot product!


Final Takeaways for Your Test

✅ Vectorized operations eliminate loops, making code faster


✅ Use , , , for element-wise operations
✅ Use
`+` `-` `*` `/`
, , for functions
✅ Broadcasting applies operations to arrays of different shapes
`np.sqrt()` `np.exp()` `np.log()`

✅ Masking allows conditional selection of elements ( `arr[arr > x]`)


✅ Use for fast dot product calculations
`np.dot()`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/25
Let me know if you need more details! 🚀

Random Functions
Pseudo-random number generation

Random Functions & Pseudo-Random Number Generation in


NumPy
NumPy provides a powerful module `numpy.random` for generating random numbers. It allows us to
create random arrays, perform sampling, and generate values from different probability
distributions.

1. What is Pseudo-Random Number Generation?


🔹 Random numbers in computers are NOT truly random.
🔹 NumPy generates numbers using a deterministic algorithm, meaning they are pseudo-random
(appear random but follow a pattern).
🔹 This is why we can control randomness using a seed value ( ), which ensures
`np.random.seed()`
reproducibility.

2. Setting a Random Seed (`np.random.seed()`)


Setting a seed value ensures that you get the same random numbers every time you run the code.

python

import numpy as np

np.random.seed(42) # Set the seed


print(np.random.rand(3))
# Output: [0.37454012 0.95071431 0.73199394] (same every time)

🔹 If you remove `np.random.seed()`, the numbers will change on every run.

3. Generating Random Numbers


(a) Generating Random Floats

1. `np.random.rand()` → Uniform distribution (0 to 1)

python

print(np.random.rand(3))
# Output: [0.4967 0.1389 0.6476] (random numbers between 0 and 1)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/25
Generating a 2D array:

python

print(np.random.rand(2, 3))
# Output:
# [[0.156 0.867 0.234]
# [0.459 0.763 0.982]]

2. `np.random.uniform(low, high, size)` → Random floats in a range

python

print(np.random.uniform(10, 20, 5))


# Output: [12.45 18.32 10.78 15.92 19.87] (between 10 and 20)

(b) Generating Random Integers

1. `np.random.randint(low, high, size)` → Random integers in a range

python

print(np.random.randint(1, 10, 5))


# Output: [4 2 9 1 6] (5 random integers between 1 and 9)

Generating a 2D array:

python

print(np.random.randint(1, 10, (3, 3)))


# Output:
# [[3 7 1]
# [5 9 2]
# [4 8 6]]

(c) Generating Random Normal (Gaussian) Distribution

1. `np.random.randn()` → Standard Normal Distribution (mean = 0, std = 1)

python

print(np.random.randn(5))
# Output: [ 0.214 -1.01 1.52 -0.56 0.78] (values follow bell curve)

2. `np.random.normal(mean, std, size)` → Custom Normal Distribution

python

print(np.random.normal(50, 10, 5))


# Output: [52.3 48.1 60.5 41.2 55.7] (mean=50, std=10)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/25
4. Random Sampling from Arrays
(a) `np.random.choice()` → Select Random Elements

python

arr = np.array([10, 20, 30, 40, 50])


print(np.random.choice(arr, 3))
# Output: [30 10 50] (random selection)

🔹 Can be used to randomly select elements from a dataset.


5. Shuffling & Permutations

(a) `np.random.shuffle()` → Shuffle an array (in-place)

python

arr = np.array([1, 2, 3, 4, 5])


np.random.shuffle(arr)
print(arr)
# Output: [3 5 1 2 4] (shuffled randomly)

(b) `np.random.permutation()` → Returns a shuffled version (not in-place)

python

arr = np.array([1, 2, 3, 4, 5])


shuffled = np.random.permutation(arr)
print(shuffled)
# Output: [5 2 4 1 3] (shuffled but original remains unchanged)

Key Takeaways for Your Test

✅ ensures reproducibility

`np.random.seed()`
`rand()`, `uniform()`, `randint()` generate random numbers
✅ `randn()` and `normal()` generate Normal (Gaussian) distributions
✅ `choice()` selects random elements from an array
✅ `shuffle()` shuffles an array in-place
✅ `permutation()` returns a shuffled copy

Let me know if you need more explanations! 🚀

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/25

You might also like