|NO.Z.00029|——————————|BigDataEnd|——|Hadoop&Python.v07|——|Arithmetic.v07|NumPy科学计算库:NumPy复制视图|

一、复制和视图:在操作数组时,有时会将其数据复制到新数组中,有时不复制。有以下三种情况
### --- 完全没有复制

import numpy as np
a = np.random.randint(0,100,size = (4,5))
b = a
a is b                                                      # 返回True a和b是两个不同名字对应同⼀个内存对象
b[0,0] = 1024                                               # 命运共同体
display(a,b)
### --- 查看或浅拷⻉
### --- 不同的数组对象可以共享相同的数据。该view⽅法创建⼀个查看相同数据的新数组对象

import numpy as np
a = np.random.randint(0,100,size = (4,5))
b = a.view()                                                # 使⽤a中的数据创建⼀个新数组对象
a is b                                                      # 返回False a和b是两个不同名字对应同⼀个内存对象
b.base is a                                                 # 返回True,b视图的根数据和a⼀样
b.flags.owndata                                             # 返回False b中的数据不是其⾃⼰的
a.flags.owndata                                             # 返回True a中的数据是其⾃⼰的
b[0,0] = 1024                                               # a和b的数据都发⽣改变
display(a,b)
### --- 深拷⻉

import numpy as np
a = np.random.randint(0,100,size = (4,5))
b = a.copy()
b is a                                                      # 返回False
b.base is a                                                 # 返回False
b.flags.owndata                                             # 返回True
a.flags.owndata                                             # 返回True
b[0,0] = 1024                                               # b改变,a不变,分道扬镳
display(a,b)
### --- copy应该在不再需要原来的数组情况下,切⽚后调⽤。例如,假设a是⼀个巨⼤的中间结果,⽽最终结果b仅包含的⼀⼩部分a,则在b使⽤切⽚进⾏构造时应制作⼀个深拷⻉:

import numpy as np
a = np.arange(1e8)
b = a[::1000000].copy()                                     # 每100万个数据中取⼀个数据
del a                                                       # 不在需要a,删除占⼤内存的a
b.shape                                                     # shape(100,)

 
 
 
 
 
 
 
 
 

Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
                                                                                                                                                   ——W.S.Landor

 

 

posted on   yanqi_vip  阅读(20)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示