Array Indexing and Slicing
Learn to access and extract specific parts of NumPy arrays
Array Indexing and Slicing
Basic Indexing
Access elements by position, starting from 0.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print("First element:", arr[0])
print("Third element:", arr[2])
print("Last element:", arr[-1])Output:
First element: 10
Third element: 30
Last element: 50
Negative indexing:
- -1 is last element
- -2 is second from end
- -3 is third from end
Modifying Elements
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
arr[0] = 99
arr[-1] = 88
print(arr)Output: [99 2 3 4 88]
Basic Slicing
Extract portions of array.
Syntax: [start:stop:step]
import numpy as np
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print("First 5:", arr[:5])
print("From index 3:", arr[3:])
print("Middle:", arr[3:7])
print("Every other:", arr[::2])
print("Reverse:", arr[::-1])Output:
First 5: [0 1 2 3 4]
From index 3: [3 4 5 6 7 8 9]
Middle: [3 4 5 6]
Every other: [0 2 4 6 8]
Reverse: [9 8 7 6 5 4 3 2 1 0]
2D Array Indexing
Access rows and columns.
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Element at (0,0):", matrix[0, 0])
print("Element at (1,2):", matrix[1, 2])
print("Element at (2,1):", matrix[2, 1])Output:
Element at (0,0): 1
Element at (1,2): 6
Element at (2,1): 8
Format: matrix[row, column]
Accessing Rows and Columns
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("First row:", matrix[0])
print("Second row:", matrix[1])
print("First column:", matrix[:, 0])
print("Second column:", matrix[:, 1])Output:
First row: [1 2 3]
Second row: [4 5 6]
First column: [1 4 7]
Second column: [2 5 8]
What : means:
- matrix[0] - first row, all columns
- matrix[:, 0] - all rows, first column
2D Slicing
Extract sub-matrices.
import numpy as np
matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print("First 2 rows, first 2 columns:")
print(matrix[:2, :2])
print("All rows, columns 1-3:")
print(matrix[:, 1:3])
print("Rows 1-2, columns 2-3:")
print(matrix[1:3, 2:4])Output:
[[1 2]
[5 6]]
[[2 3]
[6 7]
[10 11]]
[[7 8]
[11 12]]
Boolean Indexing
Filter elements using conditions.
import numpy as np
scores = np.array([78, 85, 92, 68, 95, 72])
high_scores = scores[scores > 80]
print("Scores above 80:", high_scores)
passing = scores[scores >= 70]
print("Passing scores:", passing)Output:
Scores above 80: [85 92 95]
Passing scores: [78 85 92 95 72]
How it works:
- scores > 80 creates boolean array [False, True, True, False, True, False]
- Boolean array filters original array
Multiple Conditions
Combine conditions with & (and) and | (or).
import numpy as np
prices = np.array([45, 32, 67, 28, 51, 39])
affordable = prices[(prices >= 30) & (prices <= 50)]
print("Prices 30-50:", affordable)
extreme = prices[(prices < 30) | (prices > 60)]
print("Very cheap or expensive:", extreme)Output:
Prices 30-50: [45 32 39]
Very cheap or expensive: [67 28]
Important: Use & for and, | for or, not "and"/"or".
Fancy Indexing
Select specific indices.
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60])
indices = [0, 2, 4]
selected = arr[indices]
print(selected)Output: [10 30 50]
Multiple elements at once:
arr = np.array([100, 200, 300, 400, 500])
selected = arr[[0, 3, 4]]
print(selected)Output: [100 400 500]
Modifying with Boolean Indexing
import numpy as np
scores = np.array([78, 65, 92, 58, 88])
scores[scores < 70] = 70
print("After curve:", scores)Output: [78 70 92 70 88]
What this does: All scores below 70 become 70 (grade curve).
Practice Example
The scenario: Analyze and process sales data.
import numpy as np
sales = np.array([[150, 200, 180], [220, 190, 210], [170, 240, 200]])
print("Sales Data (Days × Products)")
print(sales)
print()
print("Day 1 sales:", sales[0])
print("Product 1 sales:", sales[:, 0])
print()
total_per_day = sales.sum(axis=1)
print("Total per day:", total_per_day)
total_per_product = sales.sum(axis=0)
print("Total per product:", total_per_product)
print()
high_sales = sales[sales > 200]
print("High sales (>200):", high_sales)
print("Count of high sales:", len(high_sales))
print()
best_day_idx = total_per_day.argmax()
print("Best day:", best_day_idx + 1)
print("Best day total:", total_per_day[best_day_idx])
print()
sales[sales < 180] = 180
print("After minimum adjustment:")
print(sales)What this does:
- Shows sales data (3 days, 3 products)
- Accesses specific days and products
- Calculates daily and product totals
- Filters high-performing sales
- Finds best sales day
- Adjusts low sales to minimum
Where Function
Find positions where condition is true.
import numpy as np
arr = np.array([1, 5, 3, 8, 2, 9])
positions = np.where(arr > 4)
print("Positions where > 4:", positions)
print("Values:", arr[positions])Output:
Positions where > 4: (array([1, 3, 5]),)
Values: [5 8 9]
Conditional Assignment
import numpy as np
scores = np.array([85, 92, 78, 95, 88])
grades = np.where(scores >= 90, "A", "B")
print(grades)Output: ['B' 'A' 'B' 'A' 'B']
What this does: If score >= 90, assign "A", else assign "B".
Key Points to Remember
Indexing starts at 0. Use negative indices to count from end (-1 is last).
Slicing syntax: [start:stop:step]. stop is excluded, step is optional.
For 2D arrays: array[row, column]. Use : to select all rows or columns.
Boolean indexing filters with conditions: array[array > 5]. Use & for and, | for or.
Fancy indexing selects specific indices: array[[0, 2, 4]].
Common Mistakes
Mistake 1: Wrong 2D syntax
matrix[0][1] # Works but slow
matrix[0, 1] # Better, NumPy wayMistake 2: Using "and" instead of &
arr[(arr > 5) and (arr < 10)] # Error!
arr[(arr > 5) & (arr < 10)] # CorrectMistake 3: Forgetting parentheses
arr[arr > 5 & arr < 10] # Wrong!
arr[(arr > 5) & (arr < 10)] # CorrectMistake 4: Slice without copy
subset = arr[0:3] # This is a view
subset[0] = 99 # Changes original arr too!
subset = arr[0:3].copy() # Independent copyWhat's Next?
You now know how to access and extract array data. Next, you'll learn about array operations - mathematical operations, element-wise operations, and array arithmetic.