NumPy Basics
NumPy is the fundamental package for scientific computing in Python. It provides powerful array operations and mathematical functions.
💻 Creating Arrays
# pip install numpy
import numpy as np
# From list
arr = np.array([1, 2, 3, 4, 5])
print(arr) # [1 2 3 4 5]
# 2D array (matrix)
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix.shape) # (2, 3)
# Special arrays
zeros = np.zeros((3, 3)) # 3x3 array of zeros
ones = np.ones((2, 4)) # 2x4 array of ones
identity = np.eye(3) # 3x3 identity matrix
random = np.random.rand(3, 3) # 3x3 random values [0,1)
# Range arrays
arange = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
linspace = np.linspace(0, 1, 5) # 5 evenly spaced values🔧 Array Operations
# Element-wise operations
arr = np.array([1, 2, 3, 4])
print(arr + 10) # [11 12 13 14]
print(arr * 2) # [2 4 6 8]
print(arr ** 2) # [1 4 9 16]
# Array arithmetic
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b) # [5 7 9]
print(a * b) # [4 10 18]
# Aggregation functions
arr = np.array([1, 2, 3, 4, 5])
print(arr.sum()) # 15
print(arr.mean()) # 3.0
print(arr.std()) # 1.414...
print(arr.max()) # 5
print(arr.min()) # 1
# Matrix operations
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(A @ B) # Matrix multiplication
print(A.T) # Transpose📊 Indexing & Slicing
arr = np.array([10, 20, 30, 40, 50])
# Indexing
print(arr[0]) # 10
print(arr[-1]) # 50
# Slicing
print(arr[1:4]) # [20 30 40]
print(arr[:3]) # [10 20 30]
# Boolean indexing
print(arr[arr > 25]) # [30 40 50]
# 2D indexing
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix[0, 1]) # 2
print(matrix[:, 1]) # [2 5 8] (column)
print(matrix[1, :]) # [4 5 6] (row)🎯 Key Takeaways
- np.array(): Create NumPy array
- shape: Dimensions of array
- Element-wise ops: Fast vectorized operations
- Aggregations: sum(), mean(), std(), max(), min()
- Matrix ops: @ for multiplication, .T for transpose
- Boolean indexing: Filter with conditions
- Broadcasting: Operations on different shaped arrays