numpy array数组拷贝

1. 数组拷贝 Copy of matrix

When you do operations on an array, then you have to be careful whether or not the array is copied or only referenced to. When you change something in the copied array, then you have to be careful whether or not also the original array is changed.

There are three cases:

  • No copy at all: only a reference to the existing object. When you change anything then the original array is also changed.
  • View or shallow copy: different array objects share the same data. When you reshape the array then the change in shape is not shared with the original array, but when you change the data then the change in data is shared with the original array and the original array is also changed. A shallow copy can be made with the y = x.view() function. When you slice an array then only a view is returned and no copy of the data is made.
  • Deep copy: complete copy of array and data. When you change something in the copied array then the original array remains the same. A deep copy can be made in numpy with the y = x.copy() function.
  • copy模块中的deepcopy()则不仅仅拷贝了对象本身,还递归地拷贝了对象包含的其他对象的引用
In [4]:
# shallow copy
a = numpy.arange(10)
b = a.view()
b.shape = (2,5)
b[0, 3] = 1000
print("shallow copy: ", b)
print("original: ", a)
shallow copy:  [[   0    1    2 1000    4]
 [   5    6    7    8    9]]
original:  [   0    1    2 1000    4    5    6    7    8    9]
In [5]:
# deep copy
a = numpy.arange(10)
c = a.copy()
c.shape = (5,2)
c[3,1] = 1000
print("deep copy: ", c)
print("original: ", a)
deep copy:  [[   0    1]
 [   2    3]
 [   4    5]
 [   6 1000]
 [   8    9]]
original:  [0 1 2 3 4 5 6 7 8 9]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值