09 20241101 NumPy
09 20241101 NumPy
Computations
In other words, arrays are collections of data elements, just like lists in
Python.
Arrays in NumPy are designed for homogeneous data (same data type
across all elements) and are much more efficient for handling large
volumes of data.
NumPy Arrays in Python
What is an Array in NumPy?
NumPy arrays are n-dimensional.
Arrays can be…
Single-dimensional (1D), like a vector,
Two-dimensional (2D), like a matrix, and
Multi-dimensional (3D and beyond)
Example
import numpy as np
array_from_list = np.array([1, 2, 3, 4, 5])
NumPy Arrays in Python
Types of Array Creation
2. Predefined Arrays:
– These are methods to initialize arrays with predefined values
for faster array creation.
– Zeros and Ones: Use np.zeros() or np.ones() to initialize
arrays with zeros or ones, useful for placeholders or setting
default states.
– Empty Arrays: Created with np.empty(); these arrays are
allocated without initialization, leaving values uninitialized,
which is sometimes useful when performance is critical.
Example
zeros_array = np.zeros((3, 3))
ones_array = np.ones((2, 4))
empty_array = np.empty((2, 3))
NumPy Arrays in Python
Types of Array Creation
3. Arrays with Ranges:
– Often used in mathematical and scientific contexts to quickly
create sequences.
Example
arr = np.array([10, 20, 30, 40, 50])
print(arr[1]) # Output: 20
print(arr[-1]) # Output: 50
print(arr[1:4]) # Slice from index 1 to 3, Output: [20 30 40]
2. Indexing and Slicing
Indexing and Slicing Techniques
2. 2D Array (Matrix) Indexing::
• 2D arrays can be accessed using a pair of indices [row,
column].
Example
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix[1, 2]) # Output: 6
print(matrix[1:, :2]) # Rows 1 and onwards, first two columns
2. Indexing and Slicing
Indexing and Slicing Techniques
3. Boolean Indexing:
• This technique uses a Boolean array (of the same
shape) to filter elements.
Example
data = np.array([10, 20, 30, 40, 50])
filtered_data = data[data > 25] # Select elements greater than 25
2. Indexing and Slicing
Indexing and Slicing Techniques
4. Fancy Indexing:
• Fancy indexing allows you to select multiple elements
from an array at once by specifying a list or array of
indices.
Example
arr = np.array([0, 10, 20, 30, 40, 50])
indices = [1, 3, 4]
selected_elements = arr[indices] # Select elements at indices 1, 3, and 4
Example
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
row_indices = np.array([0, 1, 2])
col_indices = np.array([2, 1, 0])
selected_elements = matrix[row_indices, col_indices] # Select elements (0,2),
(1,1), (2,0)
print("Selected elements from matrix:", selected_elements)
3. Vectorized Operations
3. Vectorized Operations
What is Vectorization?
• Vectorization is a process that allows operations to be
performed on entire arrays or subarrays without explicit loops,
making computation faster and more concise.
Boolean Indexing
• Boolean indexing is a way to filter elements in an array based on
conditions.
Example
data = np.array([10, 20, 30, 40, 50])
filtered_data = data[data > 25] # Select elements greater than 25
print("Filtered data:", filtered_data)
4. Data Processing Using Arrays
Aggregation and Data Filtering
• Aggregation (like sum, mean, min, max) is essential for
analyzing data.
Saving Data
• Binary Format: Saves arrays in a highly efficient binary format
that preserves data types.
• Text Format: Saves arrays in text format, suitable for human-
readable files.
Example
np.save("data_array.npy", data) # Save in binary format
np.savetxt("data_array.txt", data) # Save in text format
5. Loading and Saving Data
Loading Data
• To load data back into an array, use np.load for binary files or
np.loadtxt for text files.
Example
loaded_data = np.load("data_array.npy")
loaded_text_data = np.loadtxt("data_array.txt")
print("Loaded binary data:", loaded_data)
print("Loaded text data:", loaded_text_data)
6. Linear Algebra with NumPy
6. Linear Algebra with NumPy
Matrix and Linear Algebra Operations
• NumPy has extensive linear algebra support, including matrix
multiplication, determinants, transposes and solving linear
systems.
Matrix Multiplication
• For matrix multiplication, use np.dot or the @ operator.
Example
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print("Matrix Multiplication:\n", np.dot(A, B))
6. Linear Algebra with NumPy
Matrix and Linear Algebra Operations
Transpose and Determinant
• Transpose: Flips rows and columns.
• Determinant: Calculated using np.linalg.det.
Example
print("Transpose of A:\n", A.T)
print("Determinant of A:", np.linalg.det(A))
6. Linear Algebra with NumPy
Matrix and Linear Algebra Operations
Solving Linear Equations
• For equations of the form Ax = B, for x using np.linalg.solve.
Example
B = np.array([1, 0])
x = np.linalg.solve(A, B)
print("Solution x:", x)
6. Linear Algebra with NumPy
Matrix and Linear Algebra Operations
• Linear algebra is foundational in areas like machine learning and
engineering.
• NumPy provides matrix manipulation operations and functions
for solving linear equations, which form the basis for many
machine learning algorithms.
Example
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print("Matrix Multiplication:\n", np.dot(A, B))
print("Transpose of A:\n", A.T)
print("Determinant of A:", np.linalg.det(A))
Example
# Uniformly distributed random values between 0 and 1
rand_array = np.random.rand(2, 3)
print("Uniform random values:\n", rand_array)
Example
# Random integers in a specified range
random_integers = np.random.randint(1, 10, (2, 3))
print("Random integers:\n", random_integers)