π Quick Recap (Day 19)
You mastered web scraping: fetching pages with
requests, parsing HTML with BeautifulSoup, and handling errors.
π― What Youβll Learn Today
Why NumPy arrays outperform Python lists for numerical tasks.
How to create NumPy arrays from lists or range.
Basic array operations: arithmetic, indexing, and slicing.
Common NumPy functions for statistics and reshaping.
π Why NumPy?
NumPy is the fundamental package for numerical computing in Python. Its ndarray provides:
Speed: Implemented in C, operations on arrays are vectorized and much faster than Python loops.
Memory efficiency: Arrays are stored compactly in contiguous memory.
Convenience: Do math on entire arrays without explicit loops.
Use NumPy to process large datasets, perform matrix math, and prepare data for libraries like pandas and scikit-learn.
π Creating NumPy Arrays
Install NumPy:
pip install numpyImport the library:
import numpy as npFrom a Python list:
data = [1, 2, 3, 4, 5] arr = np.array(data) print(arr, type(arr)) # array([1,2,3,4,5]) <class 'numpy.ndarray'>With arange():
arr2 = np.arange(0, 10, 2) # 0,2,4,6,8 print(arr2)With zeros() / ones():
zeros = np.zeros(5) ones = np.ones((2,3)) # 2x3 matrix print(zeros) print(ones)
π Array Operations & Indexing
NumPy supports elementwise arithmetic:
arr = np.array([1,2,3])
print(arr + 5) # [6 7 8]
print(arr * 2) # [2 4 6]Statistical functions
print(arr.mean()) # 2.0
print(arr.std()) # ~0.816
print(arr.sum()) # 6Indexing and slicing
matrix = np.arange(9).reshape(3,3)
print(matrix)
# [[0 1 2]
# [3 4 5]
# [6 7 8]]
print(matrix[1,2]) # 5
print(matrix[:,1]) # [1 4 7]
print(matrix[0]) # [0 1 2]π§ββοΈ Take the Wand and Try Yourself
Create a file
numpy_practice.py.Array creation:
Build an array of numbers 0β15.
Reshape it into a 4x4 matrix.
Elementwise math:
Add 10 to every element.
Multiply the matrix by 2.
Statistics & slicing:
Compute the mean of the entire matrix.
Extract the second column and print it.
Aggregation:
Compute the sum of each row.
Solution Example (numpy_practice.py):
import numpy as np
# Create and reshape
arr = np.arange(16).reshape(4,4)
print(arr)
# Elementwise operations
arr_plus = arr + 10
print(arr_plus)
arr_times2 = arr * 2
print(arr_times2)
# Statistics & slicing
print("Mean:", arr.mean())
print("2nd column:", arr[:,1])
# Row sums
print("Row sums:", arr.sum(axis=1))Expected output:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[10 11 12 13]
[14 15 16 17]
[18 19 20 21]
[22 23 24 25]]
[[ 0 2 4 6]
[ 8 10 12 14]
[16 18 20 22]
[24 26 28 30]]
Mean: 7.5
2nd column: [ 1 5 9 13]
Row sums: [ 6 22 38 54]Run:
python numpy_practice.pyOnce your output matches, youβve harnessed NumPy for powerful numerical computations!
Up next: Day 21: Pandas Essentials