参考链接: numpy.copy
参考链接: numpy.ndarray.copy
总结,这两个函数功能相同,都是返回一个数组的拷贝,不共享内存,两者的修改互不影响. 注意的是如果数组的元素是python普通的对象是,执行的拷贝是浅拷贝,各自对可变数据类型的修改相互是可见的,如果要执行深拷贝,需要使用copy库中的copy.deepcopy()函数.
代码实验展示:
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import numpy as np
>>> x = np.array([[1,2,3],[4,5,6]])
>>> y = x.copy()
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> x[0,0] = 2020
>>> y[0,1] = 20200910
>>> x
array([[2020, 2, 3],
[ 4, 5, 6]])
>>> y
array([[ 1, 20200910, 3],
[ 4, 5, 6]])
>>>
>>>
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> b = a.copy()
>>> a
array([1, 'm', list([2, 3, 4])], dtype=object)
>>> b
array([1, 'm', list([2, 3, 4])], dtype=object)
>>>
>>> b[2][0] = 888
>>> a[2][1] = 20200910
>>> a
array([1, 'm', list([888, 20200910, 4])], dtype=object)
>>> b
array([1, 'm', list([888, 20200910, 4])], dtype=object)
>>>
>>>
>>>
>>>
代码实验展示:
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import numpy as np
>>> x = np.array([[1,2,3],[4,5,6]])
>>> y = np.copy(x)
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> x[0,0] = 2020
>>> y[0,1] = 20200910
>>> x
array([[2020, 2, 3],
[ 4, 5, 6]])
>>> y
array([[ 1, 20200910, 3],
[ 4, 5, 6]])
>>>
>>>
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> b = np.copy(a)
>>> a
array([1, 'm', list([2, 3, 4])], dtype=object)
>>> b
array([1, 'm', list([2, 3, 4])], dtype=object)
>>> b[2][0] = 888
>>> a[2][1] = 20200910
>>> a
array([1, 'm', list([888, 20200910, 4])], dtype=object)
>>> b
array([1, 'm', list([888, 20200910, 4])], dtype=object)
>>>
>>>
>>>
>>>
>>> import copy
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> c = copy.deepcopy(a)
>>> a
array([1, 'm', list([2, 3, 4])], dtype=object)
>>> c
array([1, 'm', list([2, 3, 4])], dtype=object)
>>> c[2][0] = 888
>>> a[2][1] = 20200910
>>> a
array([1, 'm', list([2, 20200910, 4])], dtype=object)
>>> c
array([1, 'm', list([888, 3, 4])], dtype=object)
>>>
>>>
>>>