NumPy Copy vs View
When you take part of an array, NumPy has two options: hand you a view (a new array object that looks at the same memory) or a copy (new memory with duplicated values). Knowing which one you have prevents some of the most confusing bugs in NumPy code.
| Copy | View | |
|---|---|---|
| Owns its data | Yes | No, it borrows the original's memory |
| Changes affect the original | No | Yes |
| Changes to the original affect it | No | Yes |
| Cost | Allocates memory and copies values | Almost free |
| Created by | .copy(), fancy/boolean indexing, most functions |
basic slicing, .view(), usually .reshape(), .T |
Copy: independent data
import numpy as np
original = np.array([10, 20, 30, 40])
backup = original.copy()
original[0] = 99
print("original:", original)
print("backup: ", backup) # unaffectedoriginal: [99 20 30 40]
backup: [10 20 30 40]
View: shared data
A slice is a view. Writing through either name changes the same numbers:
import numpy as np
original = np.array([10, 20, 30, 40])
window = original[1:3]
window[0] = -1 # change via the view
print("original:", original)
original[2] = 777 # change via the original
print("window: ", window)original: [10 -1 30 40]
window: [ -1 777]
Why does NumPy do this? Speed and memory. Slicing a 1 GB array would be painfully slow if every slice duplicated it. Views make slicing instant.
Checking ownership with .base
Every array has a base attribute. It is None when the array owns its data; for a view it points at the array that does.
import numpy as np
a = np.arange(6)
c = a.copy()
v = a[::2]
r = a.reshape(2, 3)
print(c.base is None) # copy owns its data
print(v.base is a) # view of a
print(r.base is a) # reshape returned a view
print(np.shares_memory(a, v), np.shares_memory(a, c))True
True
True
True False
np.shares_memory(x, y) is another direct way to ask "could changing one affect the other?".
Fancy and boolean indexing make copies
Indexing with a list of positions or a boolean mask (covered in later lessons) can pick elements from anywhere, so the result can't be described as a simple view. NumPy returns a copy:
import numpy as np
a = np.array([5, 6, 7, 8])
picked = a[[0, 2]] # fancy indexing -> copy
picked[0] = 0
print(a) # unchanged
big = a[a > 6] # boolean mask -> copy
big[:] = 0
print(a) # unchanged
a[a > 6] = 0 # but assigning THROUGH a mask edits a in place
print(a)[5 6 7 8]
[5 6 7 8]
[5 6 0 0]
The last line is a common pattern worth remembering: reading with a mask gives a copy, assigning with a mask writes into the original.
A typical bug and its fix
You want to normalise part of a dataset for a calculation, but keep the raw data intact:
import numpy as np
raw = np.array([100.0, 150.0, 200.0, 250.0])
first_two = raw[:2] # a view...
first_two /= 100 # ...so this modifies raw!
print("buggy:", raw)
raw = np.array([100.0, 150.0, 200.0, 250.0])
first_two = raw[:2].copy() # an explicit copy
first_two /= 100
print("fixed:", raw, first_two)buggy: [ 1. 1.5 200. 250. ]
fixed: [100. 150. 200. 250.] [1. 1.5]
Tip: When you take a slice and plan to modify it, ask yourself whether the original should change. If not, add
.copy(). It is cheap insurance.
Test yourself
Which operation returns a view of a?
- a.copy()
- a[1:4]
- a[[1, 2, 3]]
- a[a > 0]
For an array x that owns its data, what is x.base?
- x itself
- None
- 0
- An error
a = np.zeros(3); b = a[:]; b[0] = 5 — what is a[0]?
- 0.0
- 5.0
- None
- An error