NumPy ndarray.copy()
The numpy.ndarray.copy()
method returns a copy of the array. This function is useful when you need to create an independent copy of an array rather than a reference to the original data.
Syntax
ndarray.copy(order='C')
Parameters
Parameter | Type | Description |
---|---|---|
order | str, optional | Memory layout of the copy. Options:
'C' . |
Return Value
Returns a new ndarray
object that is a copy of the original array. The copy is independent of the original array and does not share memory with it.
Examples
1. Creating a Copy of an Array
In this example, we create an array and make a copy using ndarray.copy()
. We then modify the original array to show that the copied array remains unchanged.
import numpy as np
# Create an original array
original_array = np.array([1, 2, 3, 4, 5])
# Create a copy of the array
copied_array = original_array.copy()
# Modify the original array
original_array[0] = 99
# Print both arrays
print("Original Array:", original_array)
print("Copied Array:", copied_array) # Should remain unchanged
Output:
Original Array: [99 2 3 4 5]
Copied Array: [1 2 3 4 5]
Since ndarray.copy()
creates an independent copy, changes to original_array
do not affect copied_array
.
2. Copying an Array in Fortran Order
We can use the order='F'
parameter to create a copy with Fortran-style (column-major) memory layout.
import numpy as np
# Create a 2D array
original_array = np.array([[1, 2], [3, 4]])
# Create a Fortran-order copy
copied_array = original_array.copy(order='F')
# Print memory layout of both arrays
print("Original Array Flags:\n", original_array.flags)
print("Copied Array Flags (Fortran Order):\n", copied_array.flags)
Output:
Original Array Flags:
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
Copied Array Flags (Fortran Order):
C_CONTIGUOUS : False
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
Here, the copied array is stored in Fortran order, which means it is optimized for column-major access patterns.
3. Checking If Copy Shares Memory with Original
Using np.may_share_memory()
, we can check whether two arrays share the same memory location.
import numpy as np
# Create an array
original_array = np.array([10, 20, 30, 40])
# Make a copy
copied_array = original_array.copy()
# Check memory sharing
print("Do the arrays share memory?", np.may_share_memory(original_array, copied_array))
Output:
Do the arrays share memory? False
The copied array is completely independent, ensuring that modifications to one do not affect the other.