Introduction to Python NumPy Array Copy vs View
Python NumPy Array Copy vs View
When working with arrays, it's important to understand the concepts of array copy and view.
Both copy and view provide different ways to access and manipulate array data.
Let's explore the difference between them:
Array Copy
- A copy of an array is a separate array object with its own memory.
- Modifying the copy does not affect the original array, and vice versa.
- The
copy()
function is used to create a copy of an array explicitly.
As an example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
copy_arr = arr.copy() # Create a copy of the array
copy_arr[0] = 10 # Modify the copy
print(arr) # Output: [1 2 3 4 5]
print(copy_arr) # Output: [10 2 3 4 5]
In the example above:
- Modifying the
copy_arr
does not affect the originalarr
.
Array View
- A view of an array is a different way to look at the same data.
- The view refers to the same memory location as the original array, but it has a different shape or a different way to access the data.
- Modifying the view will affect the original array, and vice versa.
- Views can be created by array slicing or using the
view()
method.
As an example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
view_arr = arr[2:] # Create a view of the array
view_arr[0] = 10 # Modify the view
print(arr) # Output: [1 2 10 4 5]
print(view_arr) # Output: [10 4 5]
In the example above:
- Modifying the
view_arr
also modifies the originalarr
.