numpy中视图和副本的区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014157109/article/details/89764385

      副本(深拷贝)是一个数据的完整的拷贝,如果我们对其进行修改,它不会影响到原始数据,物理内存(id( ))不在同一位置。

实现方式:

  1. Python 序列的切片操作;
  2. Python调用copy.deepCopy()函数(详见上一篇博客);
  3. 调用 ndarray 的 copy() 函数产生一个副本(注意:ndarray没有deepcopy()属性,同时这里的copy()是ndarray的自带属性,不需要引入copy模块;)

Example1:

import numpy as np

b = [[4,5],[1,2]]
c = np.array(b)
print('c',c)
d = c.copy()
print(c is d)
c[1][0] = 0
print('After changing:')
print('c',c)
print('d',d)
结果:
c [[4 5]
 [1 2]]
False
After changing:
c [[4 5]
 [0 2]]
d [[4 5]
 [1 2]]

Example2:注意这种一维的特殊情况,array里面的list元素发生了改变

import numpy as np

b = [4,5,[1,2]]
c = np.array(b)
print('c',c)
d = c.copy()
print(c is d)
c[2][0] = 0
print('After changing:')
print('c',c)
print('d',d)
结果:
c [4 5 list([1, 2])]
False
After changing:
c [4 5 list([0, 2])]
d [4 5 list([0, 2])]

      视图是数据的一个别称或引用,通过该别称或引用亦便可访问、操作原有数据,虽然视图和原始数据的id不同,但是如果我们对视图进行修改,它会影响到原始数据,物理内存在同一位置。

实现方式:

  1. numpy 的切片操作返回原数据的视图;
  2. 调用 ndarray 的 view() 函数产生一个视图;

Example1:对一维的ndarray对象切片:

import numpy as np 
 
arr = np.arange(12)
print ('我们的数组:')
print (arr)
print ('创建切片:')
a=arr[3:]
b=arr[3:]
a[1]=123
b[2]=234
print(arr)
print(id(a),id(b),id(arr[3:]))
我们的数组:
[ 0  1  2  3  4  5  6  7  8  9 10 11]
创建切片:
[  0   1   2   3 123 234   6   7   8   9  10  11]
4545878416 4545878496 4545878576

Example2:对二维的ndarray对象切片

import numpy as np 
 
# 最开始 a 是个 3X2 的数组
arr = np.arange(6).reshape(3,2)  
print ('数组 arr:')
print (arr)
print ('通过切片创建 arr 的视图b:')
b = arr[1:,:]  
print (b)
print ('两个数组的 id() 不同:')
print ('arr 的 id():')
print (id(arr))
print ('b 的 id():' )
print (id(b))
print('改变b的元素值后:')
b[1][0] = 9
print('arr:',arr)
print('b:',b)
结果:
数组 arr:
[[0 1]
 [2 3]
 [4 5]]
通过切片创建 arr 的视图b:
[[2 3]
 [4 5]]
两个数组的 id() 不同:
arr 的 id():
4587630880
b 的 id():
4587631200
改变b的元素值后:
arr: [[0 1]
 [2 3]
 [9 5]]
b: [[2 3]
 [9 5]]

Example3:ndarray.view() 方会创建一个新的对象,对新对象维数更改不会更改原始数据的维数。

import numpy as np 
a = np.arange(6).reshape(3,2) 

print ('Array a:' )
print (a)

print ('Create view of a:') 
b = a.view() 
print (b)  

print ('id() for both the arrays are different:' )
print ('id() of a:')
print (id(a)) 
print ('id() of b:')
print (id(b)) 

print('Change the shape of b. It does not change the shape of a ')
b.shape = 2,3 

print ('Shape of b:') 
print (b)  

print ('Shape of a:')
print (a)
结果:
Array a:
[[0 1]
 [2 3]
 [4 5]]
Create view of a:
[[0 1]
 [2 3]
 [4 5]]
id() for both the arrays are different:
id() of a:
4587632800
id() of b:
4586601568
Change the shape of b. It does not change the shape of a 
Shape of b:
[[0 1 2]
 [3 4 5]]
Shape of a:
[[0 1]
 [2 3]
 [4 5]]

参考文章:
https://www.runoob.com/numpy/numpy-copies-and-views.html
http://www.cnblogs.com/hellcat/p/8715830.html

猜你喜欢

转载自blog.csdn.net/u014157109/article/details/89764385
今日推荐