Skip to content

Latest commit

 

History

History
137 lines (100 loc) · 4.55 KB

File metadata and controls

137 lines (100 loc) · 4.55 KB

1. Introduction to NumPy and NDArrays

Tip

TL;DR (In 10 Seconds):

  • NumPy (Numerical Python) is the foundation of data science & machine learning in Python.
  • ndarray: High-performance N-dimensional array object that stores homogeneous numbers in one unbroken block of memory.
  • Speed: Up to 100x faster than standard Python lists because operations run in compiled C code without for loops.

1. Why NumPy? (Lists vs. NumPy Arrays)

Standard Python lists store references to objects scattered anywhere across computer RAM. NumPy stores homogeneous numbers in a contiguous block of memory:

  PYTHON LIST (Scattered Pointers)       NUMPY ARRAY (Contiguous Memory Block)
 ┌────────────────────────────────┐     ┌──────────────────────────────────┐
 │  [10] ──> memory 0x10A         │     │  [ 10 | 20 | 30 | 40 | 50 ]      │
 │  [20] ──> memory 0x94F         │     │  Stored continuously in a single │
 │  [30] ──> memory 0x33B         │     │  unbroken block of C memory!     │
 └────────────────────────────────┘     └──────────────────────────────────┘
Feature Python Lists NumPy Arrays (ndarray)
Memory Allocation Pointers scattered across RAM Contiguous C-array memory block
Data Types Heterogeneous (mixed types allowed) Homogeneous (strictly identical type)
Operations Slow for loops required Fast vectorized C operations
Performance High memory overhead Extremely fast & lightweight

2. Installing and Importing NumPy

Import NumPy using the universal shorthand alias np:

import numpy as np

3. Creating NumPy Arrays

A. From Python Lists (np.array)

import numpy as np

# 1D Array (Vector)
arr1d = np.array([10, 20, 30, 40])
print("1D Array:", arr1d)

# 2D Array (Matrix)
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print("2D Matrix:\n", arr2d)

B. Helper Creators (zeros, ones, full, eye, arange, linspace)

# Zeros & Ones
zeros = np.zeros((2, 3))               # 2 rows, 3 cols of 0.0
ones = np.ones((3, 2), dtype=int)       # 3 rows, 2 cols of integer 1

# Constant value & Identity matrix
full_tens = np.full((2, 2), 10)         # Filled with 10
identity = np.eye(3)                    # 3x3 Identity Matrix (1s on diagonal)

# Sequence generation
seq = np.arange(0, 10, 2)               # [0, 2, 4, 6, 8]
space = np.linspace(0.0, 1.0, 5)        # 5 evenly spaced values: [0.  0.25 0.5  0.75 1.  ]

4. Array Attributes & Type Casting (astype)

Every NumPy array exposes 4 primary attributes:

arr = np.array([[1.5, 2.5, 3.5], [4.5, 5.5, 6.5]])

print("1. Dimensions (.ndim):", arr.ndim)     # 2 (2D Matrix)
print("2. Shape (.shape):     ", arr.shape)    # (2, 3) -> 2 rows, 3 columns
print("3. Total Items (.size):", arr.size)   # 6
print("4. Data Type (.dtype): ", arr.dtype)    # float64

Explicit Type Casting (.astype)

Convert array data types efficiently:

float_arr = np.array([1.7, 2.3, 3.9])
int_arr = float_arr.astype(int)  # Truncates decimals to integers: [1, 2, 3]
print("Casted Ints:", int_arr)

5. ⚠️ Traps & Mistakes to Avoid

Trap 1: Heterogeneous List Upcasting

# If you mix integers and strings, NumPy converts ALL items to strings!
mixed = np.array([10, 20, "Python"])
print(mixed)        # ['10' '20' 'Python']
print(mixed.dtype)  # <U21 (Unicode string!) ❌ Mathematical functions will crash!

🎯 Self-Check Practice Exercise

Task: Create a 3x3 identity matrix using np.eye(3). Cast it to integer type using .astype(int) and print its .shape and .dtype.

💡 Click to See Solution
import numpy as np

matrix = np.eye(3).astype(int)

print("Identity Matrix:\n", matrix)
print("Shape:", matrix.shape)
print("Dtype:", matrix.dtype)