The copy() method returns an array copy of the given object.
copy() Syntax
The syntax of copy() is:
numpy.copy(array, order = 'K', subok = False)
copy() Arguments
The copy() method takes three arguments:
array- input datasubok(optional) - determines whether to subclass the output array if the data type is changed or to return a base-class arrayorder(optional) - specifies the order in which the elements are filled in copied class.
copy() Return Value
The copy() method returns the array interpretation of given input.
Example 1: Create Array With copy()
Output
Array copied from Array: [0 1 2 3 4] Array copied from List: [1 2 3 4 5] Array copied from Tuple: [1 2 3 4 5]
Example 2: Create Array With '=' and np.copy()
We can also create an array by copying it using the assignment operator.
Output
[-1 1 2 3 4] [-1 1 2 3 4]
As shown in the example, modifying array1 also modifies array0 because they refer to the same underlying data.
If you want to create an independent copy of array0, you can use the np.copy() function to create a deep copy explicitly
Lets see an example using np.copy().
Output
[0 1 2 3 4] [-1 1 2 3 4]
Using subok Argument in copy()
The subok parameter in copy() function determines whether the copy should be a subclass of the original array's class (True) or a basic ndarray (False).
Let's see an example.
Output
Copy with Subclass: [1 2 3] Type of Subclass: <class '__main__.CustomArray'> Copy as ndArray: [1 2 3] Type of ndArray Copy: <class 'numpy.ndarray'>
Using Optional Order Argument in copy()
The order argument specifies the order in which the copies are filled.
The order can be:
'C'- elements are stored row-wise'F'- elements are stored column-wise'A'- tries to preserve the original array's order, otherwise defaults to C-order.'K'- copies the elements in the order they occur in memory and uses C-order by default.
Note: The order argument only affects the memory layout of the copied array and does not change the values or shape of the array.