Here are 4 ways to copy arrays:
- Using assignment operator(=)
- Shallow Copy
- Deep Copy
- Using np.copy()
Method 1: Using assignment operator(=)
The assignment operator(=) doesn’t create a copy of the array. Instead, it creates a new reference to the original array.
Any changes made to either the new reference or the original array will be reflected in both, since they are actually referring to the same array in memory.
Example
import numpy as np
original_array = np.array([10, 20, 30, 40, 50])
copied_array = original_array # Using assignment operator
# Modifying the original array
original_array[0] = 5
# Both arrays are affected
print("Original Array:", original_array)
print("Copied Array:", copied_array)
Output
Original Array: [ 5 20 30 40 50]
Copied Array: [ 5 20 30 40 50]
Method 2: Shallow copy
The view() method creates a shallow copy of the array. The new array is a view of the original array’s data.
It means that any changes to the data in the new array will be reflected in the original array and vice versa.
Visual Representation
Example
import numpy as np
original_array = np.array([10, 20, 30, 40, 50])
# Creating a shallow copy of the original array using the view() method
copied_array = original_array.view()
# Modifying the first element of the original array
original_array[0] = 5
print("Original Array:", original_array)
print("Copied Array:", copied_array)
Output
Original Array: [ 5 20 30 40 50]
Copied Array: [ 5 20 30 40 50]
Method 3 : Deep copy
The copy() method creates a deep copy of the array, which means the copied array is completely independent of the original array. Therefore, modifying the new array does not affect the original array, and vice versa.
Example
import numpy as np
original_array = np.array([10, 20, 30, 40, 50])
# Creating a deep copy of the original array
copied_array = original_array.copy()
# Modifying the first element of the original array
original_array[0] = 5
# Modifying the second element of the copied array
copied_array[1] = 15
print("Original Array:", original_array)
print("Copied Array:", copied_array)
Output
Original Array: [ 5 20 30 40 50]
Copied Array: [10 15 30 40 50]
Method 4: Using np.copy()
The np.copy() function also creates a deep copy of the array, which is the same as the copy() method.
Example
import numpy as np
original_array = np.array([10, 20, 30, 40, 50])
# Usign np.copy()
copied_array = np.copy(original_array)
# Modifying the first element of the original array
original_array[0] = 5
# Modifying the second element of the copied array
copied_array[1] = 15
print("Original Array:", original_array)
print("Copied Array:", copied_array)
Output
Original Array: [ 5 20 30 40 50]
Copied Array: [10 15 30 40 50]
That’s it.