Curriculum
Course: Mastering NumPy
Login
Text lesson

Copying NumPy Array

In this lesson, you will learn.

  • Copying NumPy Array

 

Copying NumPy Array

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:

 

Shallow Copy

1. View (or shallow copy):

  • Using the 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)

 

Output

Original array: [99  2  3  4  5]
Shallow copy (view): [99  2  3  4  5]

 

Deep Copy

2. Copy (or deep copy):

  • Using the 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)

 

Output

Original array: [1 2 3 4 5]
Deep copy: [99  2  3  4  5]

 

Copying with Reference:

3. Using assignment:

  • Creating a new reference to the same array using assignment.
<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>

 

Output

Original array: [99  2  3  4  5]
Array with reference: [99  2  3  4  5]

 

Understanding Shallow Copy vs Deep Copy

 

4. copy vs view:

  • A deep copy creates a completely new array with its data, while a shallow copy creates a new array object that shares the same data with the original array.

 

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]

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review

 

 

Layer 1
Login Categories