NumPy Copy vs View

Lesson 7 of 17

Some NumPy operations give you a copy — new, independent data. Others give you a view — a new way of looking at the same data. Knowing which one you have prevents surprising bugs.

A copy is independent

Example

Python
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42

print(arr)
print(x)

Output

Plain Text
[42  2  3  4  5]
[1 2 3 4 5]

A view shares the data

Example

Python
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42

print(arr)
print(x)

Output

Plain Text
[42  2  3  4  5]
[42  2  3  4  5]

Changes flow both ways: editing the view edits the original as well.

Example

Python
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
x[0] = 31

print(arr)

Output

Plain Text
[31  2  3  4  5]

Slices are views

This is where the difference usually bites. A slice is a view, so modifying the slice modifies the original array:

Example

Python
import numpy as np

arr = np.array([10, 20, 30, 40, 50])
first_three = arr[:3]
first_three[:] = 0

print(arr)

Output

Plain Text
[ 0  0  0 40 50]

To work on part of an array without touching the original, slice and then copy: arr[:3].copy().

Check whether an array owns its data

The base attribute is None when an array owns its data, and points to the original array when it is a view:

Example

Python
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr.copy().base)
print(arr.view().base)

Output

Plain Text
None
[1 2 3 4 5]