NumPy ndarray.copy() Function:
The ndarray.copy() function of the NumPy module returns a duplicate or copy of the array.
Syntax:
numpy.ndarray.copy(order='C')
Parameters
order: This is optional. It controls the memory layout of the copy. It can accept values from ‘C’, ‘F’, ‘A’, and ‘K’. The default value is ‘C’.
- ‘C’ – denotes the C order (row major).
- ‘F’ – stands for the F order (column major).
- ‘A’ – means F if a is Fortran contiguous, otherwise, it is C.
- ‘K’ – as closely as possible it matches the layout of a.
Return Value:
A duplicate/copy of the array is returned.
NumPy ndarray.copy() Function in Python
Example
Approach:
- Import numpy module using the import keyword.
- Pass the list(multi-dimensional) as an argument to the array() function to create an array.
- Store it in a variable.
- Copy the elements of the given first array into another using the copy() function.
- Store it in a variable.
- Print the id of the given original array using the id() function.
- Print the given original array.
- Print the id of the copied array using the id() function.
- Print the copied array.
- Modify some random element of the copied array.
- Here it Modifies the element of the copied array but does not change the given original array.
- Print the given original array after modification.
- Print the copied array after modification.
- The Exit of the Program.
Below is the implementation:
# Import numpy module using the import keyword import numpy as np # Pass the list(multi-dimensional) as an argument to the array() function to create an array. # Store it in a variable. gvn_arry = np.array([[10,11,12], [13,14,15]]) # Copy the elements of the given first array into another using the copy() function # Store it in a variable. arry_copy = gvn_arry.copy() # Print the id of the given original array using the id() function print("The id of the given original array = ", id(gvn_arry)) # Print the given original array. print("The given original array:") print(gvn_arry) # Print the id of the copied array using the id() function print("The id of the copied array = ", id(arry_copy)) # Print the copied array. print("The copied array:") print(arry_copy) # Modify some random element of copied array. # Here it Modifies the element of copied array but does not # change the given original array arry_copy[0,0] = 90 # Print the given original array after modification print("The given original array after modification:") print(gvn_arry) # Print the copied array after modification. print("The copied array after modification:") print(arry_copy)
Output:
The id of the given original array = 140361216533248 The given original array: [[10 11 12] [13 14 15]] The id of the copied array = 140361216532528 The copied array: [[10 11 12] [13 14 15]] The given original array after modification: [[10 11 12] [13 14 15]] The copied array after modification: [[90 11 12] [13 14 15]]