18.NumPy之复制和视图(Copies and Views)

#NumPy之 复制和视图(Copies and Views)

import numpy as np

# ===================================================
#不拷贝的情况
a=np.arange(12)
b=a
print('b is a:')
print(b is a)

#注意两者的区别
#一
b=b.reshape((3,4))#该操作导致b不再指向a,而是由reshape生成的新数组
print(b.shape)
print(a.shape)
# (3, 4)
# (12,)

#二
b=a
b.shape=3,4 #b和a等价,都指向同一个对象,所以一变全变
print('b.shape:')
print(b.shape)
print('a.shape:')
print(a.shape)
# b.shape:
# (3, 4)
# a.shape:
# (3, 4)

# ===================================================
#浅拷贝的情况(视图、切片)
print('Shallow copy 、view or slice:')
c=a.view()
print(c)
print(c is a)
print(c.base is a)
c.shape=2,6
print(a.shape)
print(a)
# Shallow copy 、view or slice:
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
# False
# True
# (3, 4)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

#Slicing an array returns a view of it(切片返回的是数组的一个视图)


# ===================================================
#深度拷贝
print('Deep copy:')
d=a.copy()
print(d is a)
print(d.base is a)
d[0,0]=999
print('d:')
print(d)
print('a:')
print(a)
# Deep copy:
# False
# False
# d:
# [[999   1   2   3]
#  [  4   5   6   7]
#  [  8   9  10  11]]
# a:
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
posted @ 2018-03-23 15:18  wjc920  阅读(129)  评论(0编辑  收藏  举报