Examples of how to copy an array in python:
Copy an array with the numpy copy() function
To copy an array in python, a simple solution is to use the numpy function called copy(), example:
>>> import numpy as np
>>> x = np.array([1, 2, 3, 4])
>>> y = np.copy(x)
>>> y[1] = 7
>>> y
array([1, 7, 3, 4])
>>> x
array([1, 2, 3, 4])
This function will work for most of the cases except if the array is composed of iterable elements, such as a list for example:
>>> x = np.array([{'a':[1,2,3]}])
>>> y = np.copy(x)
>>> y
array([{'a': [1, 2, 3]}], dtype=object)
>>> y[0]['a'].append(4)
>>> y
array([{'a': [1, 2, 3, 4]}], dtype=object)
>>> x
array([{'a': [1, 2, 3, 4]}], dtype=object)
Note here that if the y array is modified, the x array will be as well (the function copy() is called a shallow copy).
Copy an array with deepcopy
Another solution that will return an independent copy is to use the deepcopy() function, example:
>>> import copy
>>> x = np.array([{'a':[1,2,3]}])
>>> y = copy.deepcopy(x)
>>> y
array([{'a': [1, 2, 3]}], dtype=object)
>>> y[0]['a'].append(4)
>>> y
array([{'a': [1, 2, 3, 4]}], dtype=object)
>>> x
array([{'a': [1, 2, 3]}], dtype=object)
Here y array has been modified but not the original array x.
Copy an array using the = operator
WARNING: to copy an array to not use the = operator, since the two arrays will be linked (if one array if modified the other will be too), example:
>>> import numpy as np
>>> x = np.array([1, 2, 3, 4])
>>> y = x
>>> y
array([1, 2, 3, 4])
>>> y[1] = 7
>>> y
array([1, 7, 3, 4])
>>> x
array([1, 7, 3, 4])
Here y is not really a copy of x, it is more like having two names for a same array.
References
Links | Site |
---|---|
copy | scipy doc |
Numpy matrix modified through a copy | stackoverflow |