Sub topic 4
Views versus copies
This chapter assumes you can slice arrays with a[1:3] and a[:, 1], and that you know what shape means. It covers when NumPy shares memory between arrays, when it allocates new memory, and the bugs that follow when you guess wrong.
Why the distinction exists
A NumPy array is a small header that points at a block of memory. The header records the shape, the data type, and the strides. A stride is the number of bytes to step in memory to move one position along an axis. Two headers can point at the same block with different shapes or strides.
- A view is a new array object that reads and writes the same memory as another array.
- A copy is a new array object with its own memory.
Views make slicing cheap. Taking a[:, 1] from a huge array moves no data. The cost is aliasing: writing through one name changes what the other name shows.
Basic slices are views
Basic indexing means integers, slices (start:stop:step), ..., and np.newaxis. It always returns a view.
import numpy as np
a = np.arange(12).reshape(3, 4)
col = a[:, 1] # basic slice
print(np.shares_memory(a, col)) # True
col[0] = 99
print(a[0, 1]) # 99
print(a[::2, ::2].base is not None) # True: it does not own its datanp.shares_memory(x, y) checks whether two arrays actually overlap in memory. The .base attribute holds the array that owns the memory, or None if the array owns its own data. Use shares_memory for yes/no questions. A related function, np.may_share_memory, only compares memory bounds. It is faster but can report false positives.
Boolean masks and index arrays are copies
Indexing with a boolean array or with a list or array of integers is called advanced indexing. When it appears on the right side of an expression, it returns a copy. The reason is that the selected elements are generally not laid out in memory with a regular stride, so a header alone cannot describe them.
import numpy as np
a = np.arange(10)
picked = a[a > 5] # boolean mask -> [6 7 8 9]
chosen = a[[1, 3, 5]] # integer array -> [1 3 5]
picked[0] = -1
chosen[0] = -1
print(a) # [0 1 2 3 4 5 6 7 8 9]
print(np.shares_memory(a, picked)) # False
print(np.shares_memory(a, chosen)) # FalseBoth edits changed only the copies.
Assignment through an index is different
Advanced indexing on the left side of = calls __setitem__ on the original array. That writes into the original, with no copy involved. Chaining two indexing steps breaks this.
import numpy as np
a = np.arange(10)
a[a > 5][0] = -1 # a[a > 5] builds a temporary copy, and the write goes to it
print(a) # [0 1 2 3 4 5 6 7 8 9]
a[a > 5] = -1 # one assignment on a: writes into a
print(a) # [ 0 1 2 3 4 5 -1 -1 -1 -1]The first line raises no error and has no effect. When you want to modify selected elements, put the whole selection on the left of a single =.
Reshaping, transposing and flattening
Several shape operations return a view when they can and a copy when they must.
import numpy as np
x = np.arange(6).reshape(2, 3)
t = x.T # transpose: always a view
print(np.shares_memory(x, t)) # True
print(t.flags['C_CONTIGUOUS']) # False
flat_from_t = t.reshape(-1) # needs a different memory order, so NumPy copies
print(np.shares_memory(t, flat_from_t)) # False
r = x.ravel() # view when possible
f = x.flatten() # always a copy
print(np.shares_memory(x, r), np.shares_memory(x, f)) # True FalseThe rule for reshape is that it returns a view if the new shape can be expressed as strides over the existing memory. Otherwise it copies. A C-contiguous array (rows stored one after another) can nearly always be reshaped as a view. A transposed array is not C-contiguous, so flattening it forces a copy. Your code should not depend on which case occurs. If you need independence, call .copy(). If you need to modify the original through the reshaped array, check np.shares_memory, or assign to .shape, which raises an error rather than copying.
Summary of common operations
| Operation | Result | Note |
|---|---|---|
| `a[1:3]`, `a[:, 1]`, `a[::2]` | view | Basic slicing |
| `a[..., np.newaxis]` | view | Adds a size-1 axis |
| `a.T`, `a.transpose(...)` | view | Only the strides change |
| `a.reshape(...)` | view or copy | View if strides allow |
| `a.ravel()` | view or copy | View if contiguous |
| `a.flatten()` | copy | Always |
| `a[mask]`, `a[[0, 2]]` | copy | Advanced indexing on the right side |
| `a[mask] = v` | writes into `a` | Assignment form |
| `a.copy()`, `np.array(a)` | copy | Explicit |
| `np.asarray(a)` | no copy | Returns `a` itself when it is already an ndarray of the right dtype |
| `a.astype(float)` | copy | Pass `copy=False` to skip when no change is needed |
A decision path
The diagram shows how to judge a given expression.
Bugs that come from aliasing
Functions that change their input
Operators like -= and += work in place. If a function applies one to its argument, the caller's array changes, and a view argument changes its base too.
import numpy as np
def center_in_place(v):
v -= v.mean()
return v
def center(v):
return v - v.mean() # builds a new array
data = np.array([1.0, 2.0, 3.0])
out = center(data)
print(data) # [1. 2. 3.]
center_in_place(data)
print(data) # [-1. 0. 1.]Document which version a function is. If a function must not alter its input, either avoid in-place operators or start with v = np.array(v).
Modifying a "subset" you thought was separate
Suppose you take train = data[:80] and later normalize train in place. The first 80 rows of data change too. Write data[:80].copy() when you want an independent subset.
A small view keeps a large array alive
A view holds a reference to the array that owns the memory. The owner cannot be freed while any view exists.
import numpy as np
big = np.zeros(10_000_000) # about 80 MB of float64
small = big[:10]
print(small.base is big) # True
del big # the 80 MB stays allocated, because small refers to it
small = small.copy() # now small owns 10 values and the block is freed
print(small.base is None) # TrueIf you keep a small result from a large array for a long time, copy it.
Dtype conversions and writes that disappear
astype returns a copy, so a.astype(float)[0] = 1 changes a temporary. Assigning into an array also converts the value to that array's dtype. Storing 2.7 into an integer array keeps 2. That is a separate rule from views, but it appears in the same bugs.
Checking and controlling behavior
- Use
np.shares_memory(x, y)in tests and while debugging. - Look at
x.base. If it isNone, the array owns its memory. - Check
x.flags['OWNDATA']for the same information as a boolean. - Make an array read-only with
x.flags.writeable = False. Views of it are then read-only as well, which turns silent aliasing writes into errors. - Call
.copy()at API boundaries where you want to hand off or retain data.
Practice
Exercise
What do a and b contain at the end of this code, and why?
import numpy as np
a = np.arange(6)
b = a[1:4]
b[:] = 0
c = a[[0, 5]]
c[:] = 7
Show answer
a is [0 0 0 0 4 5] and b is [0 0 0]. The slice a[1:4] is a view, so writing zeros through b overwrites positions 1 to 3 of a. The index list [0, 5] produces a copy, so setting c to [7 7] does not touch a.
Exercise
You run m[m < 0][:] = 0 to clear negative numbers in m, and nothing changes. Why, and what is the fix?
Show answer
m[m < 0] is advanced indexing on the right side of an expression, so it creates a copy. The [:] = 0 assignment writes into that temporary copy and discards it. The fix is a single assignment on the original array: m[m < 0] = 0.