Views and copies

Slices share memory; fancy and boolean index copy. base, copy, owndata.

A view is a window onto the same numbers. Change the window, and the original array changes. A copy has its own buffer.

Goal

Prove that a slice mutates its parent, and that fancy or boolean index does not.

A slice is a view

units = np.array(
    [
        [12, 7, 2],
        [9, 6, 0],
        [3, 11, 1],
    ],
    dtype=float,
)
nairobi = units[0]
nairobi[1] = 99
print("view:", nairobi)
print("parent:")
print(units)
print("view.base is units:", nairobi.base is units)

Nairobi’s product B became 99 in both arrays.

copy() detaches

units = np.array(
    [
        [12, 7, 2],
        [9, 6, 0],
        [3, 11, 1],
    ],
    dtype=float,
)
nairobi = units[0].copy()
nairobi[1] = 99
print("copy:", nairobi)
print("parent:")
print(units)
print("copy.base:", nairobi.base)

Fancy index copies

units = np.array(
    [
        [12, 7, 2],
        [9, 6, 0],
        [3, 11, 1],
    ],
    dtype=float,
)
picked = units[[0, 2]]
picked[0, 0] = -1
print("picked:")
print(picked)
print("parent:")
print(units)

Nairobi’s 12 is still 12 in units. Boolean masks (next chapter) also copy.

owndata

units = np.array([[12, 7, 2], [9, 6, 0]], dtype=float)
print("units.owndata:", units.flags["OWNDATA"])
print("slice.owndata:", units[0].flags["OWNDATA"])
print("copy.owndata:", units[0].copy().flags["OWNDATA"])
Pitfall

a[1:3] = 0 writes through the view into a. If you wanted a scratch row, call .copy() first.