Vectorized Array Operations in NumPy (Detailed Explanation)
Vectorized Array Operations in NumPy (Detailed Explanation)
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.
Introduction to NumPy:
Provides better execution speed and memory optimization compared to built-in Python lists.
Creating Arrays:
Array Properties:
Checking dimensions using `.ndim` and shape using `.shape`.
Creating arrays with specific values using `np.zeros()`, `np.ones()`, and `np.arange()`.
Array Operations:
Arithmetic operations (addition, subtraction, multiplication, division).
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:
Fancy Indexing:
Using multiple lists of indices for selection.
Vectorized Operations:
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!🚀
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:
2. Array Properties
`.ndim` (Number of dimensions)
`.shape` (Shape of array)
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
Week 4:
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! 🚀
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. 🚀
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.
NumPy provides efficient ways to store arrays in binary format using `.npy` files.
Saving an array
python
import numpy as np
Loading an array
python
If you need to save multiple arrays in a single file, use `.npz` format.
python
python
loaded = np.load('multi_arrays.npz')
print(loaded['first']) # Output: [10 20 30]
print(loaded['second']) # Output: [[1 2 3] [4 5 6]]
NumPy can save and read text files (CSV or TXT) easily.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/25
python
python
NumPy provides N-dimensional arrays (ndarrays) that allow efficient storage and manipulation of
multi-dimensional data.
1D Array (Vector)
python
import numpy as np
2D Array (Matrix)
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/25
print(arr2D.ndim) # Output: 2
3D Array (Tensor)
python
Example:
python
python
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/25
Example:
python
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
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
Using `step`
python
Using `dtype`
python
python
python
✅
✅
`np.arange(start, stop, step, dtype)`
is included, is excluded
✅ controls the difference between numbers
`start` `stop`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/25
Let me know if you need more examples! 🚀
Every NumPy array has a specific data type (`dtype`), which defines the type of values stored in it.
python
import numpy as np
python
`dtype` Description
`str` String
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/25
print(arr_float)
# Output: [1. 2. 3.]
python
python
3. `array()` Function
Creating 1D Array
python
Creating 2D Array
python
python
Instead of writing full names like `int64` or `float32`, NumPy provides short type codes.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/25
Type Code Data Type
`'f'` Float
`'b'` Boolean
python
Slicing in NumPy
Slicing in NumPy allows extracting specific elements from an array using the format:
python
array[start:stop:step]
import numpy as np
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)
python
print(arr2D[0:2, 1:3])
# Output:
# [[2 3]
# [6 7]]
python
print(arr2D[1:])
# Output:
# [[ 5 6 7 8]
# [ 9 10 11 12]]
python
print(arr2D[:, 2])
# Output: [3 7 11] (third column from each row)
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
✅ Basic slicing →
✅ Multi-dimensional slicing →
`array[start:stop:step]`
lambda functions
A lambda function (also called an anonymous function) is a small, one-line function defined using the
`lambda` keyword.
Example:
python
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()`.
python
import numpy as np
Since `map()` is not optimized for NumPy arrays, `np.vectorize()` is a better alternative.
python
💡 `np.vectorize()` applies the lambda function to each element without using loops.
python
python
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()`
1. `shape` in NumPy
The `shape` attribute of a NumPy array returns a tuple representing the dimensions of the array.
python
import numpy as np
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]]]
python
arr = np.arange(8)
reshaped = arr.reshape(2, -1) # NumPy automatically calculates the second dimension
print(reshaped.shape) # Output: (2, 4)
python
`np.arange(start, stop, step, dtype)` creates a NumPy array with a specified range.
Basic Usage
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/25
Using Float Step
python
Using `dtype`
python
NumPy provides functions to rearrange the dimensions of arrays using transposing (`.T`) and
swapping axes (`swapaxes()`).
python
import numpy as np
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)
python
python
print(swapped)
# Output:
# [[[1 5]
# [3 7]]
#
# [[2 6]
# [4 8]]]
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
Vectorized array operations (explain in detail, dont just refer to the codes i gave you)
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.
python
import numpy as np
print(result)
# Output: [6, 8, 10, 12]
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/25
2. Using Vectorized Operations (Fast & Efficient)
Element-wise Operations
python
python
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/25
🔹 Each element gets added to `10` automatically.
python
print(arr1 + arr2)
# Output:
# [[2 4 6]
# [5 7 9]]
python
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)
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
python
import numpy as np
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]]
python
python
Generating a 2D array:
python
python
print(np.random.randn(5))
# Output: [ 0.214 -1.01 1.52 -0.56 0.78] (values follow bell curve)
python
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
python
python
✅ 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
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/25