NumPy Masterclass
Introduction to NumPy
📌 What is NumPy?
NumPy stands for "Numerical Python". It provides support for large, multi-dimensional arrays and matrices.
🚀 Why use it?
- Speed: 50x faster than traditional Python lists.
- Memory: More efficient.
- Data Science Base: Pandas and Matplotlib are built ON TOP of NumPy.
🛠️ Setup
import numpy as np
arr = np.array([1, 2, 3])
print(arr)
Creating Arrays
📌 0-D to N-D Arrays
# 0-D
arr0 = np.array(42)
# 1-D
arr1 = np.array([1, 2, 3])
# 2-D (Matrix)
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
# 3-D
arr3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
Check dimensions with arr.ndim.
Indexing & Slicing
📌 Indexing
arr = np.array([1, 2, 3, 4])
print(arr[0]) # 1
print(arr[2] + arr[3]) # 7
📌 Slicing
[start:end:step]
print(arr[1:5]) # Slice from index 1 to 5 (not included)
print(arr[::2]) # Return every other element
Data Types
Common types: i (integer), b (boolean), u (unsigned integer),
f (float).
arr = np.array([1.1, 2.2, 3.3])
newarr = arr.astype('i') # Converts to integer
print(newarr) # [1 2 3]
Copy vs View
- Copy: New array, owns the data. Changes don't affect original.
- View: Just a view of original array. Changes affect original.
x = arr.copy()
y = arr.view()
Shape & Reshape
📌 Shape
Get the shape of an array.
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape) # (2, 4)
📌 Reshape
Change from 1-D to 2-D.
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
Iterating
Looping through arrays.
for x in np.nditer(arr):
print(x)
Joining & Splitting
📌 Join
arr = np.concatenate((arr1, arr2))
arr = np.stack((arr1, arr2), axis=1)
📌 Split
newarr = np.array_split(arr, 3)
Searching & Sorting
📌 Search
x = np.where(arr == 4)
📌 Sort
print(np.sort(arr))
Filtering
Getting some elements out of an existing array and creating a new array out of them.
arr = np.array([41, 42, 43, 44])
x = [True, False, True, False]
newarr = arr[x] # [41, 43]
Random Numbers
NumPy offers the random module to work with random numbers.
from numpy import random
x = random.randint(100)
y = random.rand() # Float 0 to 1
Ufuncs (Math)
Universal Functions.
# Vector Addition
x = [1, 2, 3]
y = [4, 5, 6]
z = np.add(x, y) # [5 7 9]
Also: subtract, multiply, divide, power,
mod.
Data Distributions
Generate arrays with specific probability distributions.
- Normal (Gaussian):
random.normal() - Binomial:
random.binomial() - Poisson:
random.poisson()
🚀 Real World Projects
🟢 Beginner: Matrix Calculator
Goal: Add, Subtract, Multiply 3x3 Matrices.
🟡 Intermediate: Image Manipulator
Goal: Load an image as a NumPy array and flip/rotate it.
🔴 Advanced: Neural Network from Scratch
Goal: Build a simple perceptron using dot products.
🎯 NumPy Mini Task
Goal: Array Operations.
📋 Requirements:
- Create an array with numbers 1 to 10.
- Reshape it into a 2x5 matrix.
- Multiply every number by 2.
- Print the result.
Crunch those numbers! 🔢
🎉 Congratulations!
You've completed the NumPy module.