π Introduction
When working with NumPy, understanding copy vs view is crucial.
Many beginners make mistakes here, leading to unexpected data changes.
π What is a View?
A view does not create a new array.
It references the original data.
π Any change in the view affects the original array.
π§ͺ Example of View
import numpy as nparr = np.array([1, 2, 3, 4])view = arr[1:3]
view[0] = 99print(arr)
π Output:
[ 1 99 3 4]
β Original array changed!
π What is a Copy?
A copy creates a completely new array in memory.
π Changes do NOT affect the original array.
π§ͺ Example of Copy
arr = np.array([1, 2, 3, 4])copy = arr.copy()
copy[0] = 100print(arr)
π Output:
[1 2 3 4]
β Original remains unchanged
βοΈ Key Differences
| Feature | View | Copy |
|---|---|---|
| Memory | Shared | Separate |
| Speed | Faster | Slightly slower |
| Changes affect original | Yes β | No β |
β οΈ Why This is Important?
In NumPy, slicing returns a view, not a copy.
π This can lead to:
- Bugs
- Unexpected results
- Data corruption
π§ How to Check?
print(arr.base)
β If it returns:
- Original array β it’s a view
- None β it’s a copy
π¦ Real-World Scenario
data = np.array([10, 20, 30, 40])filtered = data[1:3] # view
filtered[0] = 999print(data)
π Output:
[ 10 999 30 40]
β Data unintentionally modified β
π Used with Other Libraries
Understanding this helps when working with:
- Pandas
- TensorFlow
- Scikit-learn
π§ Pro Tips
- Use
.copy()when you donβt want changes - Be careful with slicing
- Debug using
.base