Sub topic 2
Views versus Copies
This chapter assumes basic Python, NumPy array creation, indexing, and shape inspection. A view is an array object that shares data with another array. A copy owns separate data. This difference affects whether an assignment changes the original array.
Views versus copies
Basic slicing usually creates a view. Changing the slice changes the source array. Use .copy() when you need independent data.
import numpy as np
a = np.arange(6)
view = a[1:4]
view[0] = 99
print(a) # [ 0 99 2 3 4 5]
copy = a[1:4].copy()
copy[0] = -1
print(a) # [ 0 99 2 3 4 5]Reshaping and transposing can also return views when NumPy can represent the result without copying data. Do not infer ownership from the method name. Check behavior or call .copy() explicitly when mutation must be isolated.
Boolean masks and fancy indexing
A boolean mask selects elements where a condition is True. Fancy indexing selects elements with an integer array or list. These selections generally produce copies rather than views.
a = np.array([3, -1, 4, -5, 9])
positive = a[a > 0]
selected = a[[0, 2]]
a[a < 0] = 0
print(positive) # [3 4 9]
print(selected) # [3 4]
print(a) # [3 0 4 0 9]Assignment through a mask updates the original array directly. This is often clearer and faster than a Python loop.
Vectorized arithmetic and universal functions
NumPy performs vectorized operations on whole arrays. A universal function, or ufunc, applies an operation element by element without an explicit Python loop.
x = np.array([1.0, 4.0, 9.0])
y = np.sqrt(x) + 1
print(y) # [2. 3. 4.]Broadcasting rules
Broadcasting lets NumPy combine compatible shapes. Compare dimensions from right to left. Two dimensions are compatible when they are equal or one of them is 1. Missing leading dimensions act like 1.
x = np.array([[1], [2], [3]]) # (3, 1)
y = np.array([10, 20, 30]) # (3,)
print(x + y)
# [[11 21 31]
# [12 22 32]
# [13 23 33]]Exercise
Will a[1:3] usually be a view or a copy, and how can you guarantee independent data?
Show answer
It is usually a view. Use a[1:3].copy() to guarantee independent data.