See that a NumPy slice shares its cells with the original array, use .copy() for independent edits, and change selected cells of the original with a mask in one pair of brackets.
After this lesson, you can change part of an array on purpose and keep the original returns when you need them.
Why does editing a slice change the original?
A slice of a NumPy array, such as returns[:4], is a view, a second array that shares its cells with the original, so setting AAA’s first return to zero through the slice also sets it to zero in returns. .copy() gives the rows their own cells, so an edit to the copy leaves the original as it was.
The returns are three made-up stocks’ daily returns in decimals over eight days, one column per stock, as in the lesson on return matrices. np.shares_memory(a, b) tests whether two arrays share cells. A slice of a Python list is a new list, so lists behave differently.
A small view keeps a large array in memory, so keeping a few rows of a large array calls for a copy.
How do I change selected cells of the original?
A mask selection, returns[mask], makes a copy, so writing through it in a second step, returns[mask][:, 0] = 0.0, changes the copy and leaves returns as it was. One pair of brackets, returns[mask, 0] = 0.0, writes into the original and sets AAA’s five positive returns to zero.
The mask marks the days on which AAA rose, as in the lesson on masks. returns[mask] = 0.0 without the column would zero all three stocks on those days.
The following box writes through the mask both ways.
On a copy of recorded, limit AAA’s returns to the range from −0.01 to 0.01 with np.clip, and print AAA’s return on day 4 in the copy and in recorded. You should see −0.01 and −0.0151.
TipShow answer
np.clip moves the values outside the range to the nearer limit.