Monday, October 12, 2020

Deep Copies

 

Though views are separate array objects, they save memory by sharing element data from other arrays. However, when sharing mutable values, sometimes it’s necessary to create a deep copy with independent copies of the original data. This is especially important in multi-core programming, where separate parts of your program could attempt to modify your data at the same time, possibly corrupting it.

The array method copy returns a new array object with a deep copy of the original array object’s data. First, let’s create an array and a deep copy 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.copy()
In [5]: numbers2

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

To prove that numbers2 has a separate copy of the data in numbers, let’s modify an element in numbers, then display both arrays:

In [6]: numbers[1] *= 10
In [7]: numbers

Out[7]: array([ 1, 20, 3, 4, 5])
In [8]: numbers2

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

As you can see, the change appears only in numbers.

Share:

0 comments:

Post a Comment