w3resource

NumPy: numpy.copy() function

numpy.copy() function

The numpy.copy() function is used to get an array copy of an given object.

The copy() function can be useful when you want to make changes to an array without modifying the original array. For example, if you want to perform a series of operations on an array and keep the original array intact, you can create a copy of the original array using the copy() function and perform the operations on the copy. This can also be useful when you want to pass a copy of an array to a function without modifying the original array.

Syntax:

numpy.copy(a, order='K')

Parameters:

Name Description Required /
Optional
a Input data. Required
order Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if a is Fortran contiguous, 'C’ otherwise. 'K' means match the layout of a as closely as possible. (Note that this function and ndarray.copy are very similar, but have different default values for their order= arguments.) optional

Return value:

arr : ndarray
Array interpretation of a.

Example: Shallow and Deep Copy in NumPy

>>> import numpy as np
>>> a = np.array ( [2, 3, 4])
>>> b = a
>>> c = np.copy(a)
>>> a[0] = 15
>>> b[0] == b[0]
True

The above code demonstrates shallow and deep copy in NumPy. NumPy arrays support both shallow and deep copying.
Initially, an array 'a' is created with values [2, 3, 4]. Then, a reference to 'a' is assigned to 'b', and a copy of 'a' is created using np.copy() and assigned to 'c'.
When we change the value of the first element of 'a' to 15, it reflects in 'b' as well because 'b' is just a reference to the same memory location as 'a'. So, 'b' also contains [15, 3, 4].
However, the copy 'c' is unaffected by the change in 'a' because it is a deep copy and has its own separate memory location. So, 'c' contains the original values [2, 3, 4].
The expression 'b[0] == b[0]' evaluates to True because the value at index 0 in 'b' is still 15 (same as itself).

Note that, when we modify a, b changes, but not c:

>>> import numpy as np
>>> a[0] == c[0]
False
>>> 

Python - NumPy Code Editor:

Previous: asmatrix()
Next: fromfunction()



Follow us on Facebook and Twitter for latest update.