Indexing and Slicing
"Show me only the big sales." "What happened on the last day?" Most analysis questions start by picking out part of the data. NumPy gives three ways to pick: by position, by range, and by condition.
The rule
Brackets pick by position, by range, or by a True/False mask.
By position, counting from 0. Negative numbers count from the end:
copies = np.array([3, 5, 2, 4, 1, 6, 2, 3])
copies[0] # 3
copies[-1] # 3, the last valueBy range, with a slice start:stop:step. The stop is excluded:
copies[2:5] # [2 4 1] positions 2, 3 and 4
copies[:3] # [3 5 2] from the start
copies[::2] # [3 2 1 2] every second valueIn two dimensions, give a row part and a column part separated by a comma:
grid = copies.reshape(2, 4) # [[3 5 2 4]
# [1 6 2 3]]
grid[1, 2] # 2, row 1 and column 2
grid[:, 0] # [3 1], every row, column 0
grid[0, 1:3] # [5 2]By mask: put an array of booleans inside the brackets, and only positions marked True are kept.
copies[copies > 3] # [5 4 6]
copies[(copies >= 2) & (copies <= 3)] # [3 2 2 3]Combine conditions with & (and), | (or) and ~ (not), and wrap each condition in parentheses. Python's words and and or do not work on whole arrays.
The shortcut
For a slice, subtract to count: a[start:stop] returns stop − start values. For a mask, say it as a sentence: "copies where copies is greater than 3".
State the range
We want positions 2 through 5 inclusive.
A quiet trap: a slice is a view of the same memory, not a copy. Changing part = copies[:3] then part[0] = 99 also changes copies[0]. Use .copy() when you want an independent piece.
Drills
Answer fast — trust the rule.
With copies = [3 5 2 4 1 6 2 3], what is copies[-2]?
How many values does copies[1:6] return?
With grid = [[3 5 2 4] [1 6 2 3]], what is grid[:, 1]?
Which expression keeps sales of 2 to 4 copies, both ends included?
Remember
- Brackets pick by position, by range, or by a True/False mask.
- Subtract to count a slice; say a mask out loud as a sentence.
- Slices are views: use
.copy()before changing a piece you want to keep separate.
