When operating and manipulating arrays, their data is sometimes copied into a new array and sometimes not. This is often a source of confusion for beginners. There are three cases:
No Copy at All
Simple assignments make no copy of objects or their data.
>>>a = np.array([[ 0, 1, 2, 3],
... [ 4, 5, 6, 7],
... [ 8, 9, 10, 11]])
>>>b = a # no new object is created
>>>b is a # a and b are two names for the same ndarray object
True
Python passes mutable objects as references, so function calls make no copy.
>>>deff(x):
...print(id(x))
...
>>>id(a) # id is a unique identifier of an object
148293216 # may vary
>>>f(a)
148293216 # may vary
View or Shallow Copy
Different array objects can share the same data. The view method creates a new array object that looks at the same data.
>>>c = a.view()
>>>c is a
False
>>>c.base is a # c is a view of the data owned by a
>>>s[:] = 10# s[:] is a view of s. Note the difference between s = 10 and s[:] = 10
>>>a
array([[ 0, 10, 10, 3],
[1234, 10, 10, 7],
[ 8, 10, 10, 11]])
Deep Copy
The copy method makes a complete copy of the array and its data.
>>>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]])
节约内存的技巧
Sometimes copy should be called after slicing if the original array is not required anymore. For example, suppose a is a huge intermediate result and the final result b only contains a small fraction of a, a deep copy should be made when constructing b with slicing:
>>>a = np.arange(int(1e8))
>>>b = a[:100].copy()
>>>del a # the memory of ``a`` can be released.
If b = a[:100] is used instead, a is referenced by b and will persist in memory even if del a is executed.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2022-03-22 linux_sh/bash/shell_bash参考文档/查看可用shell /命令行编辑快捷键&技巧/shell job任务管理/job vs process
2022-03-22 请编写C程序,输入5个不同的且为字符格式的学生编号,将其先由大到小排序,再将最大的学生编号和最小的学生编号互换位置,然后输出此时5位学生的编号。 输Л 输入5位学生的编号(只含数字字、英文字母或空格)
2022-03-22 linux_powershell:文件输入输出重定向/shell写入多行文本到文件中(tee/>>)/cat 操作文件/将字符串传递给命令行(<<)/流重定向(&>)