compare approaches one problem · three ways
Compare Approaches
The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.
NumPy slices: views vs copiesbehaves differently
Take the first three readings, change one, and look at the original array.
what differs
A basic NumPy slice shares memory with its array, so writing to it writes to the original. .copy() makes independent data. Python list slices are always copies, which is why the habit from lists is wrong for NumPy.
at a glance
| approach | use it when |
|---|---|
| A · slice (a view) | You want a window into the data without copying it (and you know changes show through). |
| B · slice().copy() | You'll change the piece and the original must stay as it was. |
| C · Python list slice | For comparison: list slicing always copies. |
Watch out: Fancy indexing (readings[[0, 1, 2]]) and boolean masks return copies. np.shares_memory(a, b) tells you which you have.
the outputs
Each approach runs on the same input.
concepts
viewscopiesshared memory
learn it
related comparisons
Assignment vs shallow copy vs deepcopy · Chained assignment vs .loc