Sunday, October 11, 2020

Views: Shallow Copies


View objects are objects that “see” the data in other objects, rather than having their own copies of the data. Views are also known as shallow copies. Various array methods and slicing operations produce views of an array’s data.

The array method view returns a new array object with a view of the original array object’s data. First, let’s create an array and a view of that array:

In [1]: import numpy as np
In [2]: numbers = np.arange(1, 6)
In [3]: numbers

Out[3]: array([1, 2, 3, 4, 5])

In [4]: numbers2 = numbers.view()
In [5]: numbers2

Out[5]: array([1, 2, 3, 4, 5]) 

We can use the built-in id function to see that numbers and numbers2 are different objects:

In [6]: id(numbers)
Out[6]: 4462958592

In [7]: id(numbers2)
Out[7]: 4590846240

To prove that numbers2 views the same data as numbers, let’s modify an element in numbers, then display both arrays:

In [8]: numbers[1] *= 10
In [9]: numbers2

Out[9]: array([ 1, 20, 3, 4, 5])
In [10]: numbers

Out[10]: array([ 1, 20, 3, 4, 5])

Similarly, changing a value in the view also changes that value in the original array:

In [11]: numbers2[1] /= 10
In [12]: numbers

Out[12]: array([1, 2, 3, 4, 5])
In [13]: numbers2

Out[13]: array([1, 2, 3, 4, 5])

Slice Views

Slices also create views. Let’s make numbers2 a slice that views only the first three elements of numbers:

In [14]: numbers2 = numbers[0:3]
In [15]: numbers2

Out[15]: array([1, 2, 3])

Again, we can confirm that numbers and numbers2 are different objects with id:

In [16]: id(numbers)

Out[16]: 4462958592

In [17]: id(numbers2)

Out[17]: 4590848000

We can confirm that numbers2 is a view of only the first three numbers elements by attempting to access numbers2[3], which produces an IndexError:

In [18]: numbers2[3]
-------------------------------------------------
------------------------

IndexError Traceback
(most recent call last)
<ipython-input-16-582053f52daa> in <module>()
----> 1 numbers2[3]
IndexError: index 3 is out of bounds for axis 0 with size 3

Now, let’s modify an element both arrays share, then display them. Again, we see that numbers2 is a view of numbers:

In [19]: numbers[1] *= 20
In [20]: numbers

Out[20]: array([1, 2, 3, 4, 5])

In [21]: numbers2
Out[21]: array([ 1, 40, 3])


Share:

0 comments:

Post a Comment