NumPy Array View or Shallow Copy. The following shows how to create a view or shallow copy of a NumPy array of the Python NumPy module.
import numpy as np
In [7]:
a = np.arange(12)
b = a
b is a
Out[7]:
True
In [8]:
a
Out[8]:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
In [9]:
b.shape = 3,4
a.shape
Out[9]:
(3, 4)
In [10]:
a
Out[10]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [11]:
def f(x):
print(id(x))
id(a)
Out[11]:
140043709957584
In [12]:
f(a)
Out[12]:
140043709957584
View or Shallow Copy:
In [15]:
c = a.view()
c is a
Out[15]:
False
In [16]:
a
Out[16]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [17]:
c
Out[17]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [18]:
c.base is a
Out[18]:
True
In [19]:
c.flags.owndata
Out[19]:
False
In [20]:
a.flags.owndata
Out[20]:
True
In [21]:
c.shape = 2,6
a.shape
Out[21]:
(3, 4)
In [22]:
c[0,4] = 1234
a
Out[22]:
array([[ 0, 1, 2, 3],
[1234, 5, 6, 7],
[ 8, 9, 10, 11]])
In [23]:
s = a[ : , 1:3]
s[:] = 10
a
Out[23]:
array([[ 0, 10, 10, 3],
[1234, 10, 10, 7],
[ 8, 10, 10, 11]])
In [24]:
s
Out[24]:
array([[10, 10],
[10, 10],
[10, 10]])