Posted under » Python Data Analysis on 15 June 2023
From Indexing and slicing
You can use the view method to create a new array object that looks at the same data as the original array (a soft copy).
NumPy functions, as well as operations like indexing and slicing, will return views whenever possible. This saves memory and is faster (no copy of the data has to be made).
However it’s important to be aware of this - modifying data in a view also modifies the original array! Let’s say you create this array:
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) b1 = a[0, :] b1 array([1, 2, 3, 4]) b1[0] = 99 b1 array([99, 2, 3, 4]) a array([[99, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]])
To avoid this, use the copy method. It will make a complete copy of the array and its data (a hard copy).
b2 = a.copy()