numpy basicsPython

numpy basics

data science ml

Run notebook
numpy basics

Converted from 01_numpy_basics.ipynb for web reading.

Code cell 1

import numpy as np
print(f"NumPy version: {np.__version__}")

Creating Arrays

Code cell 3

# From Python lists
arr1d = np.array([1, 2, 3, 4, 5])
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(f"1D Array: {arr1d}")
print(f"2D Array:\n{arr2d}")
print(f"Shape: {arr2d.shape}, Dtype: {arr2d.dtype}")

Code cell 4

# Special arrays
zeros = np.zeros((2, 3))
ones = np.ones((2, 3))
identity = np.eye(3)
range_arr = np.arange(0, 10, 2)
linspace = np.linspace(0, 1, 5)

print(f"Zeros:\n{zeros}")
print(f"\nIdentity:\n{identity}")
print(f"\nRange: {range_arr}")
print(f"Linspace: {linspace}")

Code cell 5

# Random arrays
np.random.seed(42)
random_uniform = np.random.rand(3)       # [0, 1) uniform
random_normal = np.random.randn(3)       # Normal distribution
random_int = np.random.randint(1, 10, 5) # Random integers

print(f"Random uniform: {random_uniform}")
print(f"Random normal: {random_normal}")
print(f"Random integers: {random_int}")

Array Operations (Vectorized)

Code cell 7

a = np.array([1, 2, 3, 4, 5])
b = np.array([10, 20, 30, 40, 50])

print(f"a = {a}")
print(f"b = {b}")
print(f"a + b = {a + b}")
print(f"a * b = {a * b}")
print(f"a ** 2 = {a ** 2}")
print(f"np.sqrt(a) = {np.sqrt(a)}")

Code cell 8

# Aggregations
print(f"sum: {a.sum()}, mean: {a.mean():.2f}, std: {a.std():.2f}")
print(f"min: {a.min()}, max: {a.max()}")
print(f"cumsum: {np.cumsum(a)}")

Indexing and Slicing

Code cell 10

arr = np.array([[1, 2, 3, 4],
                [5, 6, 7, 8],
                [9, 10, 11, 12]])

print(f"Array:\n{arr}")
print(f"\narr[0, 0] = {arr[0, 0]}")
print(f"arr[1, 2] = {arr[1, 2]}")
print(f"First row: {arr[0, :]}")
print(f"First column: {arr[:, 0]}")
print(f"Subarray [0:2, 1:3]:\n{arr[0:2, 1:3]}")

Boolean Indexing

Code cell 12

data = np.array([1, 5, 3, 8, 2, 9, 4, 7])
print(f"Data: {data}")
print(f"data > 5: {data > 5}")
print(f"data[data > 5] = {data[data > 5]}")

Broadcasting

Code cell 14

# Different shapes automatically align
matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])
row = np.array([10, 20, 30])
col = np.array([[100], [200], [300]])

print(f"Matrix:\n{matrix}")
print(f"\nMatrix + row:\n{matrix + row}")
print(f"\nMatrix + col:\n{matrix + col}")

Reshaping

Code cell 16

arr = np.arange(12)
print(f"Original: {arr}")

reshaped = arr.reshape(3, 4)
print(f"\nReshaped (3, 4):\n{reshaped}")
print(f"\nTransposed:\n{reshaped.T}")
print(f"\nFlattened: {reshaped.flatten()}")