In this lesson, you will learn.
NumPy provides several methods for copying arrays. It’s important to understand the difference between a shallow copy and a deep copy.
Let’s explore various copying methods with examples:
view()
method to create a new array object that looks at the same data.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
arr_view = arr.view()
arr_view[0] = 99 # Modifying arr_view also modifies arr
print("Original array:", arr)
print("Shallow copy (view):", arr_view)
Original array: [99 2 3 4 5]
Shallow copy (view): [99 2 3 4 5]
copy()
method to create a complete copy of the array and its data.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
arr_copy = arr.copy()
arr_copy[0] = 99 # Modifying arr_copy does not affect arr
print("Original array:", arr)
print("Deep copy:", arr_copy)
Original array: [1 2 3 4 5]
Deep copy: [99 2 3 4 5]
<pre class="wp-block-syntaxhighlighter-code"><br>import numpy as np
arr = np.array([1, 2, 3, 4, 5])
arr_reference = arr
arr_reference[0] = 99 # Modifying arr_reference also modifies arr
print("Original array:", arr)
print("Array with reference:", arr_reference)
</pre>
Original array: [99 2 3 4 5]
Array with reference: [99 2 3 4 5]
copy
vs view
:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Deep copy
arr_deep_copy = arr.copy()
arr_deep_copy[0] = 99
# Shallow copy
arr_shallow_copy = arr.view()
arr_shallow_copy[0] = 88
print("Original array:", arr)
print("Deep copy:", arr_deep_copy)
print("Shallow copy (view):", arr_shallow_copy)
Output
Original array: [88 2 3 4 5]
Deep copy: [99 2 3 4 5]
Shallow copy (view): [88 2 3 4 5]
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.