Understanding when a view or copy for a Numpy array is returned is important, or else the array may be modified in place by mistake. An example below:
import numpy as npprint("Numpy version: ", np.__version__)def print_result(test_array): a = test_array.copy() b = a[0] b +=1print(f'b = a[0], {"unchanged"if np.allclose(a, test_array) else"changed"}', ) a = test_array.copy() b = a[[0]] b +=1print(f'b = a[[0]], {"unchanged"if np.allclose(a, test_array) else"changed"}', ) a = test_array.copy() b = a[0:1] b +=1print(f'b = a[0:1], {"unchanged"if np.allclose(a, test_array) else"changed"}', )print("For 1D array:")print_result(np.zeros(2))print("-"*10)print("For 2D array:")print_result(np.zeros((2, 2)))
Numpy version: 1.23.1
For 1D array:
b = a[0], unchanged
b = a[[0]], unchanged
b = a[0:1], changed
----------
For 2D array:
b = a[0], changed
b = a[[0]], unchanged
b = a[0:1], changed
Note that the result is different for 1D or 2D Numpy arrays.
@online{li2024,
author = {Li, Chengkun},
title = {A {Numpy} Caveat When Referencing Elements of an Array},
date = {2024-02-23},
url = {https://pipme.github.io/posts/2024-02-23-Numpy-caveat/index-gist.html},
langid = {en}
}