13 KiB
NumPy views and copies¶
- Operations that only require changing the metadata always do so, and return a view
- Operations that cannot be executed by changing the metadata create a new memory block, and return a copy
import numpy as np
def print_info(a):
""" Print the content of an array, and its metadata. """
txt = f"""
dtype\t{a.dtype}
ndim\t{a.ndim}
shape\t{a.shape}
strides\t{a.strides}
"""
print(a)
print(txt)
x = np.arange(12).reshape(3, 4).copy()
print_info(x)
Views¶
Operations that only require changing the metadata always do so, and return a view
y = x[0::2, 1::2]
print_info(y)
A view shares the same memory block as the original array.
CAREFUL: Modifying the view changes the original array and all an other views of that array as well!
z = x.reshape(1, 12)
print_info(z)
y += 100
print_info(y)
print_info(x)
print_info(z)
Functions that take an array as an input should avoid modifying it in place!
Always make a copy or be super extra clear in the docstring.
def robust_log(a, cte=1e-10):
""" Returns the log of an array, avoiding troubles when a value is 0.
Add a tiny constant to the values of `a` so that they are not 0.
`a` is expected to have non-negative values.
"""
a[a == 0] += cte
return np.log(a)
a = np.array([[0.3, 0.01], [0, 1]])
np.log(a)
# This is a view of `a`
b = a[1, :]
print_info(b)
robust_log(a)
a
b
Better to make a copy!
def robust_log(a, cte=1e-10):
""" Returns the log of an array, avoiding troubles when a value is 0.
Add a tiny constant to the values of `a` so that they are not 0.
`a` is expected to have non-negative values.
"""
a = a.copy()
a[a == 0] += cte
return np.log(a)
a = np.array([[0.3, 0.01], [0, 1]])
b = a[1, :]
robust_log(a)
a
b
Copies¶
Operations that cannot be executed by changing the metadata create a new memory block, and return a copy
x = np.arange(12).reshape(3, 4).copy()
print_info(x)
Choosing row, columns, or individual elements of an array by giving explicitly their indices (a.k.a "fancy indexing") it's an operation that in general cannot be executed by changing the metadata alone.
Therefore, fancy indexing always returns a copy.
# Get the first and second column
y = x[:, [0, 1]]
print_info(y)
y += 1000
print_info(y)
# the original array is unchanged => not a view!
print_info(x)
y = x[[0, 0, 2], [1, 0, 3]]
print_info(y)
y += 1000
print_info(y)
# the original array is unchanged => not a view!
print_info(x)
Any operation that computes new values also returns a copy.
y = x * 7.1
print_info(y)