CoachnestCoachnest
For OrganizationsSign InGet Started
Back to course

Python for Data Science & Machine Learning

…
—
Contents
1

Python Setup & Language Basics

ReadingFree
2

Data Types, Functions & OOP

Video20m
3

Python Fundamentals Quiz

Quiz10m

NumPy Arrays & Vectorised Operations

Reading18m
5

Pandas DataFrames — Data Wrangling

Video25m
6

Cleaning & Transforming Real Datasets

Reading20m
7

Scikit-learn — ML in 30 Minutes

Video30m
8

Building & Evaluating Your First Model

Reading22m
9

Data Science & ML Knowledge Check

Quiz15m
←→navigate lessons
Chapter 2 of 3·Data Analysis with Pandas
Lesson 4 of 9Reading18 min

NumPy Arrays & Vectorised Operations

#NumPy Arrays & Vectorised Operations¶

NumPy (Numerical Python) is the backbone of scientific computing in Python. It provides the ndarray — a fast, memory-efficient multi-dimensional array.

Why Not Just Use Python Lists?¶

python
14 lines
1import numpy as np
2import time
3
4# Python list — slow
5data = list(range(1_000_000))
6start = time.time()
7result = [x * 2 for x in data]
8print(f"List: {time.time() - start:.3f}s")  # ~0.08s
9
10# NumPy array — fast
11arr = np.arange(1_000_000)
12start = time.time()
13result = arr * 2          # vectorised — no Python loop!
14print(f"NumPy: {time.time() - start:.3f}s") # ~0.002s  (40x faster)

Creating Arrays¶

python
14 lines
1import numpy as np
2
3# From a Python list
4a = np.array([1, 2, 3, 4, 5])
5
6# Ranges
7b = np.arange(0, 10, 2)          # [0, 2, 4, 6, 8]
8c = np.linspace(0, 1, 5)         # [0., 0.25, 0.5, 0.75, 1.]
9
10# Special arrays
11zeros  = np.zeros((3, 4))         # 3×4 matrix of 0s
12ones   = np.ones((2, 2))          # 2×2 matrix of 1s
13eye    = np.eye(3)                 # 3×3 identity matrix
14random = np.random.randn(100)      # 100 standard-normal samples

Array Maths¶

python
8 lines
1a = np.array([10, 20, 30, 40])
2b = np.array([ 1,  2,  3,  4])
3
4print(a + b)      # [11, 22, 33, 44]
5print(a * b)      # [10, 40, 90, 160]
6print(a / b)      # [10., 10., 10., 10.]
7print(a ** 2)     # [100, 400, 900, 1600]
8print(np.sqrt(a)) # [3.16, 4.47, 5.47, 6.32]

Indexing & Slicing¶

python
11 lines
1matrix = np.array([[1, 2, 3],
2                   [4, 5, 6],
3                   [7, 8, 9]])
4
5print(matrix[1, 2])      # 6  (row 1, col 2)
6print(matrix[:, 1])      # [2, 5, 8]  (all rows, column 1)
7print(matrix[0:2, 0:2])  # top-left 2×2 submatrix
8
9# Boolean indexing
10data = np.array([15, 42, 7, 88, 23])
11print(data[data > 20])   # [42, 88, 23]

Common Aggregations¶

python
8 lines
1prices = np.array([299, 499, 999, 149, 799])
2
3print(prices.mean())    # 549.0
4print(prices.std())     # 312.7
5print(prices.min())     # 149
6print(prices.max())     # 999
7print(prices.sum())     # 2745
8print(np.median(prices))# 499.0

Previous

Python Fundamentals Quiz

Next

Pandas DataFrames — Data Wrangling

Use ← → arrow keys to navigate between lessons