Overview
Take the last seven days of a sensor log, and learn why changing a NumPy slice can silently change your original data.
- a[start:stop] and negative indexes
- Slices are views
- .copy() for independent data
Short Course
Slicing works like it does on lists, but a NumPy slice is a view. Trap:
writing into the slice changes the original array. Call .copy() when you
need separate data.
log = np.array([3, 5, 8, 1])
part = log[-2:] # array([8, 1])
part[0] = 0
log # array([3, 5, 0, 1]): changed!
safe = log[-2:].copy()
Task
Write last_week(daily) that returns a copy of the last 7 values of an array,
for example last_week(np.arange(10)) gives array([3, 4, 5, 6, 7, 8, 9]).
Test Suites
Pending
Next
Output