拷贝
# 拷贝分类
NumPy 中拷贝分为三种情况:
完全不拷贝
一个数组的任何变化都反映在另一个数组上,包括值变化和形状变化
浅拷贝
一个数组值会变化会反映在另一个数组上,但是形状不变化
深拷贝
创建原数组的副本,副本的任何变化都不会反映在原数组上
# 示例
import numpy as np
1
# 完全不拷贝
a = np.arange(12)
b = a
a
b
1
2
3
4
5
2
3
4
5
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
b[5] = 500
a
b
1
2
3
2
3
array([ 0, 1, 2, 3, 4, 500, 6, 7, 8, 9, 10, 11])
array([ 0, 1, 2, 3, 4, 500, 6, 7, 8, 9, 10, 11])
b is a
1
True
b.shape = (2, 6)
a
b
1
2
3
2
3
array([[ 0, 1, 2, 3, 4, 500],
[ 6, 7, 8, 9, 10, 11]])
array([[ 0, 1, 2, 3, 4, 500],
[ 6, 7, 8, 9, 10, 11]])
# 浅拷贝
a = np.arange(12)
c = a.view()
a
c
1
2
3
4
5
2
3
4
5
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
c is a
1
False
c.base is a
1
True
c[2] = 200
a
c
1
2
3
2
3
array([ 0, 1, 200, 3, 4, 5, 6, 7, 8, 9, 10, 11])
array([ 0, 1, 200, 3, 4, 5, 6, 7, 8, 9, 10, 11])
c.shape = (12, 1)
a
c
1
2
3
2
3
array([ 0, 1, 200, 3, 4, 5, 6, 7, 8, 9, 10, 11])
array([[ 0],
[ 1],
[200],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[ 10],
[ 11]])
# 深拷贝
a = np.arange(12)
d = a.copy()
a
d
1
2
3
4
5
2
3
4
5
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
d is a
1
False
a[1] = 100
a
d
1
2
3
2
3
array([ 0, 100, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
d.shape = (12, 1)
a
d
1
2
3
2
3
array([ 0, 100, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
array([[ 0],
[ 1],
[ 2],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[10],
[11]])
上次更新: 2023/11/01, 03:11:44
← NumPy 数组计算 索引和切片→