Array Indexing and Slicing
What You'll Learn
You'll learn how to extract specific elements, rows, columns, and sections from NumPy arrays—essential for selecting features and samples from your ML datasets.
Why This Matters for ML
In machine learning, your data lives in arrays. A dataset might have thousands of rows (samples) and dozens of columns (features). You constantly need to grab specific parts: maybe just the first 100 training examples, or only the third feature column, or a batch of images. Array indexing and slicing are your precision tools for this surgery.
Basic Indexing
Just like Python lists, NumPy arrays use square brackets. For a 1D array, arr[2] gets the element at index 2 (remember: zero-indexed). For a 2D array (like a dataset), you use arr[row, column].
Example pattern:
data[0]→ first sample (entire row)data[:, 0]→ first feature (entire column)data[5, 3]→ the value at row 5, column 3
Slicing: Taking Ranges
Slicing uses the colon : syntax. start:stop:step grabs a range (stop is exclusive).
Common ML patterns:
data[0:100]→ first 100 samples (training batch)data[:, 2:5]→ columns 2, 3, 4 (subset of features)data[10:50, :]→ samples 10-49, all featuresdata[::2]→ every other sample
Think of It Like This
Imagine your dataset is a spreadsheet. Indexing is pointing at a single cell. Slicing is highlighting a rectangular region—you choose which rows and columns to include.
Key Takeaway: Array indexing and slicing let you surgically extract exactly the samples and features you need from your ML datasets—mastering these operations is fundamental to data manipulation in machine learning.