copy
方法制作完整數(shù)組的副本及其數(shù)據(jù)。
>>> d = a.copy() # a new array object with new data is created
>>> d is a
False
>>> d.base is a # d doesn't share anything with a
False
>>> d[0, 0] = 9999
>>> a
array([[ 0, 10, 10, 3],
[1234, 10, 10, 7],
[ 8, 10, 10, 11]])
copy
如果不再需要原始數(shù)組,有時(shí)應(yīng)該在切片后調(diào)用。例如,假設(shè)a
是一個(gè)巨大的中間結(jié)果,而最終結(jié)果b
只包含 的一小部分a
,則在b
使用切片構(gòu)造時(shí)應(yīng)進(jìn)行深拷貝:
>>> a = np.arange(int(1e8))
>>> b = a[:100].copy()
>>> del a # the memory of ``a`` can be released.
如果b?=?a[:100]
被使用,a
則被b
引用并且即使del a
被執(zhí)行a
也會(huì)保留在內(nèi)存中。
更多建議: