Indexing views and copies
Quick answer
Indexing retrieves elements or subarrays. Basic slicing commonly returns a view, which shares the original array’s data. Advanced indexing with integer arrays or boolean masks returns a copy when used to read. Use .copy() when a transformation must not change the original features. Scalar indexing returns a scalar rather than a subarray view.
A slice can change its parent
A slice uses start:stop:step with the stop excluded. The colon selects every row; the column interval 0:1 retains a length-one axis. np.shares_memory checks whether the two nonempty arrays overlap.
import numpy as npx = np.array([[2, 8], [4, 9], [6, 10]])view = x[:, 0:1]print(view.shape, np.shares_memory(x, view))view[0, 0] = 99safe = x[:, 0].copy()safe[1] = -1print(x.tolist())Expected output (local NumPy 2.3.5):
(3, 1) True[[99, 8], [4, 9], [6, 10]]Writing the view changes the first feature of sample zero. Changing the explicit copy leaves sample one unchanged.
Select and reorder samples
Integer lists select positions in the supplied order, including repeats. A boolean mask selects positions whose condition is true. Here the row condition uses the first feature.
import numpy as npx = np.array([[2, 8], [4, 9], [6, 10]])selected = x[[2, 0, 2]]selected[0, 0] = -1print(selected.tolist())print(x[x[:, 0] >= 4].tolist())print(np.shares_memory(x, selected))Expected output (local NumPy 2.3.5):
[[-1, 10], [2, 8], [6, 10]][[4, 9], [6, 10]]FalseThe repeated row is copied twice; modifying one selected row does not alter the source. Masking returns two rows here.
Common mistakes
x[:, 0] removes the column axis; x[:, 0:1] keeps it. Advanced indexing on the left of assignment, such as x[[0, 2]] = 0, writes to the original even though reading those indices produces a copy. Reshape may return either a view or a copy; transposed data may not be contiguous. Do not assume .base alone proves two arbitrary arrays overlap. Small views can keep large backing buffers alive.
Practice and next steps
Given four sensor rows, select rows 3 and 1 in that order and alter a value in the selected array. Verify the original is unchanged. Next, use broadcasting to transform features consistently.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Indexing views and copies — knowledge check
Apply array reasoning to new synthetic feature tables.
What is the shape of x[:, 1:2] if x has shape (4, 3)?
Which read usually shares storage with a numeric ndarray x?
What happens when x[[0, 2]] = 0 executes on a writable matrix?
How do you select row 2 twice, then row 0?
What is safest before mutating a numeric slice that must not alter its parent?