Sub topic 4
Views versus copies
This chapter assumes you can index and slice arrays, as covered in the previous chapter. It also assumes you know that a Python name refers to an object and does not hold a separate copy of it.
Why the distinction matters
A NumPy array has two parts. One is a block of memory that holds the numbers. The other is a small header that records the shape, dtype and strides (how far to step in memory to reach the next element along each axis).
A view is a new header that points at the same memory block. A copy is a new header with its own new block. Writing through a view changes the original array. Writing to a copy does not.
Views are cheap, because no data moves. The cost is that an edit made through one name can change data you are using under another name.
Basic slices return views
Slices built from integers, start:stop:step and ... return views.
import numpy as np
a = np.arange(12).reshape(3, 4)
col = a[:, 1] # basic slice: a view
col[0] = 99
print(a[0, 1]) # 99, the original changed
print(np.shares_memory(a, col)) # TrueFancy indexing, meaning integer arrays and boolean masks, always returns a copy. NumPy cannot describe an arbitrary selection of elements with a fixed step, so it gathers the values into new memory.
import numpy as np
a = np.arange(12).reshape(3, 4)
big = a[a > 5] # boolean mask: a copy
big[0] = -1
print(a[a > 5][0]) # 6, unchanged by the edit to big
print(np.shares_memory(a, big)) # False
rows = a[[0, 2]] # integer-array index: also a copy
rows[0, 0] = 100
print(a[0, 0]) # 0Checking and controlling sharing
np.shares_memory(x, y)reports whether two arrays use the same memory.x.baseis the array that owns the memory, orNoneifxowns its data.x.copy()makes an independent copy.
import numpy as np
a = np.arange(6)
v = a[1:4]
c = a[1:4].copy()
print(v.base is a) # True
print(c.base is None) # True
v[:] = 0
print(a) # [0 0 0 0 4 5]
print(c) # [1 2 3]Assignment works differently from selection
Fancy indexing on the left side of an assignment writes into the original array. Only reading with fancy indexing makes a copy.
import numpy as np
a = np.arange(10)
a[a > 6] = 0 # modifies a in place
print(a) # [0 1 2 3 4 5 6 0 0 0]This is why a[mask][0] = 5 silently does nothing useful. The expression a[mask] creates a temporary copy, and the write goes into that copy. Use a[mask] = 5 to modify a.
Common errors
- Editing a slice and corrupting the source. Call
.copy()before changing a slice you want to keep separate. - Keeping a tiny slice of a huge array. The view keeps the whole memory block alive. Copy the slice if you want the large array freed.
- Chained fancy indexing on assignment. As shown above, the write lands on a temporary copy.
- Assuming
reshapealways copies or always shares. It returns a view when the memory layout allows it and a copy otherwise. Do not depend on either behavior.
Exercise
Given a = np.arange(5), you run b = a[1:3], then b[0] = 50, then c = a[[1, 2]], then c[1] = 70. What does a contain at the end?
Show answer
[0 50 2 3 4]. The slice b is a view, so setting b[0] changes a[1]. The integer-array index creates a copy c, so setting c[1] does not affect a.