Complete NumPy Tutorial
Master all NumPy essentials with short, practical examples!
🔢 Welcome to NumPy!
NumPy makes working with numbers super easy! Think of it as a calculator that can handle thousands of numbers at once.
import numpy as np
numbers = np.array([1, 2, 3, 4, 5])
print(numbers * 2) # [2 4 6 8 10]
Fast
Computing
Easy
To Learn
Powerful
Math Tools
Getting Started
Install and Import
# Install: pip install numpy
import numpy as np
print("NumPy version:", np.__version__)
Creating Arrays
Different Ways to Create Arrays
# From lists
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([[1, 2], [3, 4]]) # 2D array
# Built-in functions
zeros = np.zeros(5) # [0. 0. 0. 0. 0.]
ones = np.ones((2, 3)) # 2x3 array of ones
range_arr = np.arange(0, 10, 2) # [0 2 4 6 8]
linear = np.linspace(0, 1, 5) # 5 numbers from 0 to 1
Random Arrays
# Random arrays
random_floats = np.random.random(5) # Random 0-1
random_ints = np.random.randint(1, 10, 5) # Random integers
normal = np.random.normal(0, 1, 5) # Normal distribution
Array Properties
Understanding Your Arrays
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Shape:", arr.shape) # (2, 3)
print("Size:", arr.size) # 6
print("Dimensions:", arr.ndim) # 2
print("Data type:", arr.dtype) # int64
Accessing Array Elements
Indexing and Slicing
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # 10 (first element)
print(arr[-1]) # 50 (last element)
print(arr[1:4]) # [20 30 40] (slice)
# 2D indexing
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d[0, 1]) # 2 (row 0, column 1)
print(arr2d[:, 0]) # [1 4] (all rows, column 0)
Boolean Indexing
arr = np.array([1, 5, 3, 8, 2, 9])
mask = arr > 4
print(mask) # [False True False True False True]
print(arr[mask]) # [5 8 9] (elements > 4)
print(arr[arr % 2 == 0]) # [8 2] (even numbers)
Math Operations
Basic Math
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
print(a + b) # [6 8 10 12]
print(a * b) # [5 12 21 32]
print(a ** 2) # [1 4 9 16]
print(np.sqrt(a)) # [1. 1.41 1.73 2.]
Universal Functions
arr = np.array([1, 4, 9, 16])
print(np.sqrt(arr)) # [1. 2. 3. 4.]
print(np.exp(arr)) # Exponential
print(np.log(arr)) # Natural log
print(np.sin(arr)) # Sine function
Statistics
Basic Statistics
scores = np.array([85, 90, 78, 92, 88, 76, 95])
print("Mean:", scores.mean()) # 86.29
print("Median:", np.median(scores)) # 88.0
print("Std:", scores.std()) # 6.42
print("Min/Max:", scores.min(), scores.max())
Axis-wise Operations
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print("Sum all:", matrix.sum()) # 21
print("Sum rows:", matrix.sum(axis=1)) # [6 15]
print("Sum cols:", matrix.sum(axis=0)) # [5 7 9]
print("Mean cols:", matrix.mean(axis=0)) # [2.5 3.5 4.5]
Reshaping Arrays
Shape Manipulation
arr = np.arange(12) # [0 1 2 3 4 5 6 7 8 9 10 11]
reshaped = arr.reshape(3, 4) # 3x4 matrix
print(reshaped)
# Transpose
print(reshaped.T) # Flip rows and columns
print(arr.reshape(-1, 1)) # Column vector (-1 = auto)
Flattening
matrix = np.array([[1, 2, 3], [4, 5, 6]])
flat = matrix.flatten() # [1 2 3 4 5 6]
ravel = matrix.ravel() # Same as flatten
print("Original shape:", matrix.shape)
print("Flat shape:", flat.shape)
Combining Arrays
Stacking Arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Horizontal and vertical stacking
h_stack = np.hstack([a, b]) # [1 2 3 4 5 6]
v_stack = np.vstack([a, b]) # [[1 2 3], [4 5 6]]
print("Horizontal:", h_stack)
print("Vertical:\n", v_stack)
Concatenate
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
# Concatenate along different axes
concat_rows = np.concatenate([arr1, arr2], axis=0) # Stack rows
concat_cols = np.concatenate([arr1, arr2], axis=1) # Stack columns
print("Rows:\n", concat_rows)
print("Cols:\n", concat_cols)
Broadcasting
Broadcasting Rules
# Broadcasting allows operations on different sized arrays
arr = np.array([[1, 2, 3], [4, 5, 6]])
scalar = 10
vector = np.array([1, 2, 3])
print(arr + scalar) # Add 10 to all elements
print(arr + vector) # Add vector to each row
print(arr * vector) # Multiply each row by vector
🎯 Real-World Examples
Image Processing Basics
# Simulate a grayscale image (values 0-255)
image = np.random.randint(0, 256, (5, 5))
print("Original image:\n", image)
# Brighten image
bright = np.clip(image + 50, 0, 255)
print("Brightened:\n", bright)
Financial Data
# Stock prices over 5 days
prices = np.array([100, 102, 98, 105, 103])
returns = (prices[1:] - prices[:-1]) / prices[:-1] * 100
print("Prices:", prices)
print("Daily returns (%):", returns.round(2))
print("Average return:", returns.mean().round(2))
Grade Analysis
# Student grades: rows=students, cols=subjects
grades = np.array([[85, 90, 78], [92, 88, 95], [76, 82, 89]])
student_avg = grades.mean(axis=1) # Average per student
subject_avg = grades.mean(axis=0) # Average per subject
print("Student averages:", student_avg.round(1))
print("Subject averages:", subject_avg.round(1))
print("Class average:", grades.mean().round(1))
Best Practices
📝 Import as np
Always use
import numpy as np
🚀 Vectorize Operations
Use NumPy functions instead of loops
💾 Choose Right dtype
Use appropriate data types to save memory
🔍 Check Shapes
Always verify array shapes before operations