import numpy as np
Copy vs. View in NumPyΒΆ
Understanding the difference between copies and views is critical for avoiding subtle bugs. A view (created with .view() or basic slicing) shares the same underlying memory as the original array β modifying one modifies the other. A copy (created with .copy()) allocates entirely new memory, so changes are independent. Views are memory-efficient for large datasets since no data is duplicated, but they can cause unexpected side effects if you mutate the view thinking it is independent. When in doubt, use .copy() to ensure your transformations do not corrupt original data.
# Copy Vs. View
np1 = np.array([0,1,2,3,4,5])
'''
# Create a view
np2 = np1.view()
print(f'Original NP1: {np1}')
print(f'Original NP2: {np2}')
# change np1
np2[0] = 41
print(f'Changed NP1: {np1}')
print(f'Original NP2: {np2}')
'''
# Make a copy
np2 = np1.copy()
print(f'Original NP1: {np1}')
print(f'Original NP2: {np2}')
# change np1
np2[0] = 41
print(f'Changed NP1: {np1}')
print(f'Original NP2: {np2}')