Numpy 简明教程

NumPy - Copies & Views

在执行函数时,其中一些返回输入数组的副本,而另一些返回视图。当内容物理存储在另一个位置时,称为 Copy 。另一方面,如果提供了相同内存内容的不同视图,则我们将其称为 View

No Copy

简单赋值不会生成数组对象的副本。相反,它使用原始数组的相同id()来访问它。 id() 返回Python对象的通用标识符,类似于C语言中的指针。

此外,一个中的任何更改都会反映在另一个中。例如,改变一个的形状也将改变另一个的形状。

Example

import numpy as np
a = np.arange(6)

print 'Our array is:'
print a

print 'Applying id() function:'
print id(a)

print 'a is assigned to b:'
b = a
print b

print 'b has same id():'
print id(b)

print 'Change shape of b:'
b.shape = 3,2
print b

print 'Shape of a also gets changed:'
print a

它将生成如下输出:

Our array is:
[0 1 2 3 4 5]

Applying id() function:
139747815479536

a is assigned to b:
[0 1 2 3 4 5]
b has same id():
139747815479536

Change shape of b:
[[0 1]
 [2 3]
 [4 5]]

Shape of a also gets changed:
[[0 1]
 [2 3]
 [4 5]]

View or Shallow Copy

NumPy具有 ndarray.view() 方法,该方法是一个新的数组对象,它查看原始数组的相同数据。与之前的案例不同,新数组尺寸的变化不会改变原始数组的尺寸。

Example

import numpy as np
# To begin with, a is 3X2 array
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)

# 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:
140424307227264
id() of b:
140424151696288

Shape of b:
[[0 1 2]
 [3 4 5]]

Shape of a:
[[0 1]
 [2 3]
 [4 5]]

数组的分片创建视图。

Example

import numpy as np
a = np.array([[10,10], [2,3], [4,5]])

print 'Our array is:'
print a

print 'Create a slice:'
s = a[:, :2]
print s

它将生成如下输出:

Our array is:
[[10 10]
 [ 2 3]
 [ 4 5]]

Create a slice:
[[10 10]
 [ 2 3]
 [ 4 5]]

Deep Copy

ndarray.copy() 函数创建深度副本。它是数组及其数据的完整副本,并且不与原始数组共享。

Example

import numpy as np
a = np.array([[10,10], [2,3], [4,5]])

print 'Array a is:'
print a

print 'Create a deep copy of a:'
b = a.copy()
print 'Array b is:'
print b

#b does not share any memory of a
print 'Can we write b is a'
print b is a

print 'Change the contents of b:'
b[0,0] = 100

print 'Modified array b:'
print b

print 'a remains unchanged:'
print a

它将生成如下输出:

Array a is:
[[10 10]
 [ 2 3]
 [ 4 5]]

Create a deep copy of a:
Array b is:
[[10 10]
 [ 2 3]
 [ 4 5]]
Can we write b is a
False

Change the contents of b:
Modified array b:
[[100 10]
 [ 2 3]
 [ 4 5]]

a remains unchanged:
[[10 10]
 [ 2 3]
 [ 4 5]]