NumPy Copies and Views
A copy is a complete copy of the data. If we modify the copy, it will not affect the original data; they are not at the same physical memory location.
A view is an alias or reference to the data. Through this alias or reference, you can access and manipulate the original data, but no copy of the original data is made. If we modify the view, it will affect the original data; they are at the same physical memory location.
Views generally occur in the following cases:
- 1. NumPy slice operations return a view of the original data.
- 2. Calling the ndarray view() function produces a view.
Copies generally occur in the following cases:
- Python sequence slicing operations, and calling the deepCopy() function.
- Calling the ndarray copy() function produces a copy.
No Copy
Simple assignment does not create a copy of the array object. Instead, it uses the same id() as the original array to access it. id() returns a generic identifier for a Python object, similar to a pointer in C.
In addition, any changes to one array are reflected on the other array. For example, changing the shape of one array will also change the shape of the other array.
Example
The output result is:
我们的数组是: [0 1 2 3 4 5] 调用 id() 函数: 4349302224 a 赋值给 b: [0 1 2 3 4 5] b 拥有相同 id(): 4349302224 修改 b 的形状: [[0 1] [2 3] [4 5]] a 的形状也修改了: [[0 1] [2 3] [4 5]]
View or Shallow Copy
The ndarray.view() method creates a new array object. Changing the dimensions of the new array created by this method does not change the dimensions of the original data.
Example
The output result is:
数组 a: [[0 1] [2 3] [4 5]] 创建 a 的视图: [[0 1] [2 3] [4 5]] 两个数组的 id() 不同: a 的 id(): 4314786992 b 的 id(): 4315171296 b 的形状: [[0 1 2] [3 4 5]] a 的形状: [[0 1] [2 3] [4 5]]
Using slices to create views and modifying data will affect the original array:
Example
The output result is:
我们的数组: [ 0 1 2 3 4 5 6 7 8 9 10 11] 创建切片: [ 0 1 2 3 123 234 6 7 8 9 10 11] 4545878416 4545878496 4545878576
Variables a and b are both views of parts of arr. Modifications to the views are directly reflected in the original data. But if we observe the ids of a and b, they are different. That is, although views point to the original data, they are still different from assignment references.
Copy or Deep Copy
The ndarray.copy() function creates a copy. Modifying the copy data does not affect the original data; they are not at the same physical memory location.
Example
The output result is:
数组 a: [[10 10] [ 2 3] [ 4 5]] 创建 a 的深层副本: 数组 b: [[10 10] [ 2 3] [ 4 5]] 我们能够写入 b 来写入 a 吗? False 修改 b 的内容: 修改后的数组 b: [[100 10] [ 2 3] [ 4 5]] a 保持不变: [[10 10] [ 2 3] [ 4 5]]
More Related Articles
Analysis of Python Direct Assignment, Shallow Copy, and Deep Copy
Other Extensions