NumPy — Indexing & Slicing
Master coordinate-based array selection in Python: zero-based and negative indexing in 1D and 2D arrays, the start:stop:step slicing formula, extracting entire rows and columns with :, and subsetting multidimensional numerical datasets for real-world business analytics.
1. Indexing — Accessing Individual Values
Just like standard Python sequences, NumPy arrays use zero-based indexing. The first element is at index 0, the second at index 1, and so on. NumPy also supports negative indexing to count backward from the end.
arr = np.array([10, 20, 30, 40, 50])Click any element to inspect indexarr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # -> 10 (first item)
print(arr[1]) # -> 20 (second item)
print(arr[4]) # -> 50 (fifth item)
print(arr[-1]) # -> 50 (last item)
print(arr[-2]) # -> 40 (second-to-last item)
N, the valid positive indices are 0 to N - 1. Accessing arr[N] raises an IndexError: index is out of bounds.2. 🔥 Live Indexing Practice
Given an array of monthly sales figures: sales = np.array([45000, 32000, 78000, 25000, 60000]). Write the indexing expressions to complete each task below. Do not hardcode values!
3. Slicing — The start:stop:step Formula
Slicing allows you to extract a subset of an array into a new view. The general syntax is:
arr[:3]), defaults to 0.stop is NEVER included. If omitted (e.g. arr[2:]), defaults to the end of the array.1. A negative step (e.g. -1) steps backward.arr[1:4] # -> [20 30 40] (indices 1, 2, 3; 4 is excluded)
arr[:3] # -> [10 20 30] (start at 0, take first 3 elements)
arr[2:] # -> [30 40 50 60] (start at index 2, take to the end)
arr[::2] # -> [10 30 50] (every second item)
arr[::-1] # -> [60 50 40 30 20 10] (reverses the array!)
4. 🔥 Live Slicing Practice & Predictions
Given sales = np.array([10, 20, 30, 40, 50, 60]). First test your intuition with the predictions below, then run actual Python code!
5. 🔥 2D Array Indexing — Coordinates [row, column]
In two dimensions (matrices/tables), NumPy uses comma-separated coordinates inside a single bracket:data[row, column]. Both row and column indices start at 0.
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
])
print(data[0, 0]) # -> 10 (top-left element)
print(data[1, 2]) # -> 60 (row 1, column 2)
print(data[2, 1]) # -> 80 (row 2, column 1)
print(data[1]) # -> [40 50 60] (omitting column selects the ENTIRE row!)
6. 🔥 2D Slicing — Selecting Sub-Matrices & Full Dimensions
To slice in 2D, specify a slice range for rows and columns separated by a comma:data[row_start:row_stop, col_start:col_stop]. Use a bare colon : to select an entire dimension.
data[:, 1]The : means "all rows". Column index 1 selects column 1 from every row. Returns a 1D vector: [20 50 80].
data[1, :]Selects row index 1 across all columns (:). Returns: [40 50 60].
data[0:2, 1:3]Extracts rows 0 and 1 (stop 2 excluded) and columns 1 and 2 (stop 3 excluded). Returns a 2×2 matrix: [[20 30], [50 60]].
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
])
# Extract sub-matrix (rows 0,1; cols 1,2)
print(data[0:2, 1:3])
# Output:
# [[20 30]
# [50 60]]
# First two rows across all columns
print(data[:2, :])
# Output:
# [[10 20 30]
# [40 50 60]]
7. 🔥 Live 2D Indexing & Slicing Lab
Given sales = np.array([[100, 200, 300], [400, 500, 600], [700, 800, 900]]). Write the expressions to accomplish each task below:
8. Indexing vs. Slicing — The Core Mental Model
A very common beginner question is: "When do I use indexing vs slicing?". Here is the golden rule:
| Operation | Purpose | 1D Example | 2D Example | Result Dimension |
|---|---|---|---|---|
| Indexing | Selects a single specific element (or single row) | arr[2] | data[1, 2] | Collapses dimension (returns a scalar value or 1D row) |
| Slicing | Selects a range or window of multiple elements | arr[1:4] | data[0:2, 1:3] | Preserves rectangular array dimensionality (returns a sub-array) |
:) in either index position (e.g. data[1, 2]), you are picking a single scalar value. If it has a colon (e.g. data[1:2, :]), you are picking an array window.9. Practical Data Analytics: Branch Sales Analysis
In real-world data science, a 2D NumPy array often represents a structured numerical table. Here, each row represents a retail branch, and each column represents quarterly revenue (in $K).
| Branch (Row) | Q1 (Col 0) | Q2 (Col 1) | Q3 (Col 2) |
|---|---|---|---|
| North (Row 0) | $120K | $150K | $180K |
| Central (Row 1) | $200K | $220K | $250K |
| South (Row 2) | $90K | $110K | $130K |
- "What was Central's Q2 revenue?" →
sales[1, 1]→ 220 - "Extract Branch South's yearly numbers" →
sales[2, :]→ [90 110 130] - "Extract Q1 numbers across all branches" →
sales[:, 0]→ [120 200 90] - "Isolate H1 (Q1 & Q2) for North & Central" →
sales[:2, :2]
10. 🔥 Final Live Challenge: Comprehensive 2D Subsetting
Test your mastery on a 3×4 numerical matrix:
data = np.array([ [10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120] ])
Complete all 5 tasks without looking at the solution:
- Select the value 70 (row 1, column 2)
- Select the last row (row index -1)
- Select the second column across all rows (col index 1)
- Select the first two rows across all columns
- Select the middle 2×2 section:
[[60, 70], [100, 110]]
11. Common Mistakes & Pitfalls to Avoid
Keep these 5 frequent pitfalls in mind when indexing and slicing numerical arrays:
The 3rd element is at index 2, not index 3. Writing arr[3] fetches the 4th element!
arr[0:3] produces 3 elements (indices 0, 1, 2). It stops before index 3.
Always write data[row, col]. Beginners frequently accidentally write data[col, row], leading to transposed or out-of-bounds selections.
While Python lists require list[r][c], in NumPy always write data[r, c]. data[r][c] creates an unnecessary intermediate temporary 1D array.
12. Knowledge Assessment Quiz
Verify your conceptual understanding of NumPy indexing, negative strides, and 2D slicing:
NumPy Indexing & Slicing Certification Quiz
Test your understanding with real-world query prediction and syntax questions.
Given arr = np.array([10, 20, 30, 40, 50]), what does arr[1:4] return?