Lesson 08
Copy and View
Tell a copy from a view with base and shares_memory, see why a slice changes its original, and pick between flatten and ravel.
A copy is a new array that owns its values. A view is another way of looking at the same values. Change the original, and a view changes with it. A copy does not.
copy owns its data
Changes to the original do not reach the copy, and changes to the copy do not reach the original.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr)
print(x)Output:
[42 2 3 4 5]
[1 2 3 4 5]view shares the data
A view reads the same memory. A change on either side shows on both.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
y = arr.view()
arr[0] = 42
print(y)
y[1] = 31
print(arr)Output:
[42 2 3 4 5]
[42 31 3 4 5]Check who owns the data
base is None when an array owns its data. For a view, base is the array it came from. A basic slice is a view too. np.shares_memory(a, b) answers the question directly.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
y = arr.view()
part = arr[1:3]
print(x.base)
print(y.base is arr)
print(part.base is arr)
print(np.shares_memory(arr, x), np.shares_memory(arr, part))Output:
None
True
True
False Trueflatten and ravel
Both turn a multi-dimensional array into 1-D, reading row by row. flatten always returns a copy. ravel returns a view when it can, which is faster and uses no extra memory. That also means a change to the raveled array can reach the original.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
flat = arr.flatten()
flat[0] = 10
print(flat)
print(arr)
line = arr.ravel()
line[0] = 20
print(line)
print(arr)Output:
[10 2 3 4 5 6]
[[1 2 3]
[4 5 6]]
[20 2 3 4 5 6]
[[20 2 3]
[ 4 5 6]]Key takeaways
-
A copy owns its data, so
baseisNone -
A view and a basic slice share data with the original
-
flattencopies.ravelreturns a view when it can -
Use
.copy()before editing a piece you want to keep separate -
Next: Sorting and Comparing
-
Previous: Advanced Indexing
Loading playground…
Check your understanding
Copy and View Quiz
What is x.base for x = arr.copy()?
1 / 10