Sub topic 5
Views versus copies: when slicing shares memory
This chapter assumes you can create arrays with np.arange and reshape, and that you know basic slicing with start:stop:step. It covers a question every NumPy user hits sooner or later: when you select part of an array, do you get your own data or a window onto the original?
The working model
A NumPy array is a small header (shape, strides, dtype) that points at a block of memory. A view is a new header that points at the same block. A copy is a new header with its own new block.
Writing through a view changes the original array. Writing through a copy does not.
Basic slices return views
Any selection made only with integers and slices returns a view. This is fast and uses no extra memory, because no data moves.
import numpy as np
a = np.arange(12).reshape(3, 4)
view = a[:, :2]
view[0, 0] = 99
print(a[0, 0]) # 99, because a slice is a view of a
print(np.shares_memory(a, a[:, :2])) # TrueThe write to view[0, 0] shows up in a[0, 0]. This is often what you want, for example when you fill one region of a large array in place. It is a bug when you expected a separate array.
Reshaping and transposing also return views when NumPy can describe the result without moving data. Treat reshape as "usually a view" and do not rely on it either way.
Copies: `.copy()` and fancy indexing
Call .copy() when you need an independent array.
import numpy as np
a = np.arange(12).reshape(3, 4)
a[0, 0] = 99
independent = a[:, :2].copy()
independent[0, 0] = -1
print(a[0, 0]) # still 99
rows = a[[0, 1]] # fancy indexing returns a copy
rows[0, 0] = -5
print(a[0, 0]) # still 99Indexing with a list or array of integers (fancy indexing) always returns a copy. Boolean mask selection, which later chapters cover, also returns a copy.
| Selection | Result |
|---|---|
| `a[1, 2]` | Scalar value (a copy of that element) |
| `a[:, :2]`, `a[::2]`, `a[..., 0]` | View |
| `a[[0, 1]]`, `a[[0, 2], [1, 3]]` | Copy |
| `a[a > 5]` | Copy |
| `a[:, :2].copy()` | Copy |
Checking what you have
Two tools tell you whether memory is shared.
np.shares_memory(x, y)checks whether the arrays actually overlap in memory.x.baseis the array that owns the data whenxis a view. For an array that owns its data,x.baseisNone.
import numpy as np
a = np.arange(6)
v = a[1:4]
c = a[[1, 2, 3]]
print(v.base is a) # True
print(c.base is None) # TrueA subtle case: assignment versus selection
Fancy indexing on the left side of an assignment writes into the original. The copy rule applies only when you select values out.
import numpy as np
a = np.arange(6)
a[[0, 2]] = 100 # writes into a
print(a) # [100 1 100 3 4 5]
b = a[[0, 2]] # selects a copy
b[0] = -1
print(a) # unchanged: [100 1 100 3 4 5]A chained form is a common trap. In a[[0, 2]][0] = 5, the first step a[[0, 2]] makes a temporary copy, and the write goes into that copy. The original a is not changed, and no error is raised. Use a single index expression, such as a[0] = 5, instead.
When to copy
- Copy when you will modify a slice and need the original unchanged.
- Copy when a small slice of a very large array must outlive the large array. A view keeps the whole original block in memory, so the large array cannot be freed.
- Do not copy when you only read the data. A view is cheaper.
Exercise
Given a = np.arange(10), you run s = a[2:5] and f = a[[2, 3, 4]], then s[0] = 50 and f[1] = 60. What are a[2] and a[3]?
Show answer
a[2] is 50 and a[3] is 3. The slice s is a view, so writing s[0] changes a[2]. The fancy-indexed f is a copy, so writing f[1] leaves a[3] unchanged.
Exercise
Why does a[[0, 2]][0] = 5 leave a unchanged, and how would you write the intended change?
Show answer
a[[0, 2]] uses fancy indexing, which returns a temporary copy. The assignment [0] = 5 modifies that copy, which is then discarded. Write a[0] = 5 to change the original.